Function to randomly place a ship/sub at a new location

All discussions & material related to Command's Lua interface

Moderators: michaelm75au, angster, RoryAndersonCDT, MOD_Command

Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

Function to randomly place a ship/sub at a new location

Post by Whicker »

This seems to work fairly well with subs/ships/groups of ships.

Uses ScenEdit_AddReferencePoint's ability to specify a distance in miles as well as a bearing from a current unit. So take your unit, create a random distance up to x, and a random bearing between x and y, put a RP there and then check its depth. If the depth is less than your desired depth then move the unit there. if the depth is not acceptable then try it again (limit 50 tries).

It is not checking to make sure all units in a group are properly located at sea - so if you have a dispersed group, the units furthest from the lead have a chance of being on land. You could control this with the distance and bearings to make sure the new location is away from land. If it is a single unit there is no problem.

Since it is a function you should be able to put all units you want to have randomized into a table and then loop thru the table and call the function on each one at scen start.

If the unit is on a plotted course, that carries over to the new location - it will head to the same waypoint it was before being moved.

Somewhat tested.

-----
function placeShipRandomly(side, ship, distance, bmin, bmax, mindepth)
math.randomseed(os.time())
local triggerUnit = ScenEdit_GetUnit({name=ship})
if triggerUnit ~= nil then
local redo_count = 0 --prevents infinite loop/game freeze
::redo::
local d = math.random(1,distance)
local b = math.random(bmin,bmax)
local point = ScenEdit_AddReferencePoint( {side=side, name='possible'..redo_count, RelativeTo=ship, bearing=b ,distance=d })
-- using addRP's ability to set the points bearing and distance relative to an existing unit as the new location for the unit
ScenEdit_DeleteReferencePoint ({side=side, name='possible'..redo_count}) --should be ok to delete, just need the values
elevation = World_GetElevation({latitude=point.latitude, longitude=point.longitude}) -- get elevation of new RP to see if it is suitable
print(elevation)
if elevation < mindepth then -- check if the new points depth is ok, if so assign the unit to the RPs lat/long
triggerUnit.latitude = point.latitude
triggerUnit.longitude = point.longitude
return --exit as we are done
end
--print(point)
redo_count = redo_count + 1 --if we get this far the elevation check failed
if redo_count >50 then --prevents infinite loop/game freeze
print ('unit was not able to find a suitable spot for placement, ship not moved')
return
else
goto redo --retries the placement if the water is too shallow
end
else
print("Unit does not exist")
end
end


local side = 'Blue'
local ship = 'Group 106' --can be group or individual ship or sub
local distance = 250 -- max distance in miles away from starting point
local bearignMin = 1 -- you can control the direction by adjusting the min and max bearing
local bearingMax = 360 -- 1 and 360 is anywhere around, 90,180 would be anywhere below etc.
local minDepth = -1000 --meters, negative

placeShipRandomly(side, ship, distance, bearignMin, bearingMax, minDepth) -- call the function and pass in the parameters
-----
KnightHawk75
Posts: 1850
Joined: Thu Nov 15, 2018 7:24 pm

RE: Function to randomly place a ship/sub at a new location

Post by KnightHawk75 »

Nice. Thanks, always looking for helpful functions and fragments.
I also forgot goto exists in the language, good reminder.
--

In the same spirit here's a variant of your's that can take most facilities and aircraft in addition to sub and ships as well as optionally randomize the depth\altitude of sub\aircraft. Some of that randomization of depth\alt has hardcoded min\max but a luauser could quickly change that or add additional params for them.
I also added parameter defaults and some range checking, makes calling function easier from different places of code in that on can count on defaults, see sample calls below.

Code:

function placeUnitRandomly(side, ship, distance, bmin, bmax, mindepth,randomalt)
if (side == nil or side=='') or (ship == nil or ship =='') then
print('lua function placeUnitRandomly() missing side or ship or unit name. Aborting call.');
return
end

if (bmin == nil or bmin < 0 or bmin > 360) then bmin = 1 end --if missing or invaid use 1 as default
if (bmax == nil or bmax < 0 or bmax > 360) then bmax = 360 end -- if missing or invalid use 360 as default
if (mindepth == nil or mindepth < -10000 or mindepth > 0) then mindepth = -2 end -- if missing or invalid use -2m default
if (distance == nil or distance < 1 or distance > 12000) then distance = 100 end -- if missing or invalid use 100nm default
randomalt = randomalt or false;
math.randomseed(os.time());

local triggerUnit = ScenEdit_GetUnit({name=ship});
if triggerUnit ~= nil then
local redo_count = 0 --prevents infinite loop/game freeze
::redo::
local d = math.random(1,distance);
local b = math.random(bmin,bmax);
local point = ScenEdit_AddReferencePoint( {side=side, name='possible'..redo_count, RelativeTo=ship, bearing=b ,distance=d });
-- using addRP's ability to set the points bearing and distance relative to an existing unit as the new location for the unit
ScenEdit_DeleteReferencePoint ({side=side, name='possible'..redo_count}); --should be ok to delete, just need the values
elevation = World_GetElevation({latitude=point.latitude, longitude=point.longitude}); -- get elevation of new RP to see if it is suitable
--print(elevation)
if triggerUnit.type == 'Aircraft' then
--ignore elevation
print('moving an aircraft')
triggerUnit.latitude = point.latitude;
triggerUnit.longitude = point.longitude;
if (randomalt) then
local ralt = math.random(305,10975.7); -- ~ 1000 to 36000 ft
triggerUnit.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship, moveto=true,altitude=ralt}) --set desired alt to current.
end
return --exit as we are done
elseif (triggerUnit.type == 'Facility' and triggerUnit.subtype ~= '4001') then
if (elevation > 0) then
-- facility that is not sosus bottom array? and needs to be above ground level; could be other subtypes to flag??.
--print('moving an non submerged facility')
triggerUnit.latitude = point.latitude;
triggerUnit.longitude = point.longitude;
return --exit as we are done
end
elseif (elevation < mindepth) then -- check if the new points depth is ok, if so assign the unit to the RPs lat/long
--assume ship or sub
--print('moving an ship, sub or submerged facility')
triggerUnit.latitude = point.latitude;
triggerUnit.longitude = point.longitude;
if (randomalt and triggerUnit.type == 'Submarine') then
if (elevation < -450 ) then elevation = -450 end; --cap max depth at like ~1475ft when it's much deeper.
if (elevation >= mindepth) then mindepth = -3 end; --reset min depth to like 10ft if elevation > min depth; change to 0 if want chance of surfaced subs.
local ralt = math.random(elevation,mindepth); --grab rando betweeen bottom and mindepth;
--print('changing altitude on ' .. ship .. ' to ' .. tostring(ralt) );
triggerUnit.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship,moveto=true, depth=(ralt * -1)}); --set desired depth to current depth req postive
end
return --exit as we are done
end

--print(point)
redo_count = redo_count + 1; --if we get this far the elevation check failed
if redo_count >50 then --prevents infinite loop/game freeze
print ('unit was not able to find a suitable spot for placement, ship not moved');
return
else
goto redo; --retries the placement if the water is too shallow
end
else
print("Unit does not exist");
end
--endfunc
end

--Sample usage examples
--Change side and ship to match one's own text objects.
--
local side = 'US';
--local ship = 'A-100 Premier [Il-476]' --can be group or individual ship or sub aircraft;
local ship = 'SSN 774 Virginia [Flight I]'; --sub max depth ~1475
--local ship = 'Bottom Fixed Array (SOSUS)'; subtype 4001 test;
--local ship = 'DDG 96 Bainbridge [Arleigh Burke Flight IIA]'; --surface ship
--local ship = 'Bunker (ACINT SOSUS Station)'; --subtype 3001 test
--local ship = 'Flight 18'; --group of 2 a-100 aircraft

local distance = 150; -- max distance in miles away from starting point
local bearignMin = 1; -- you can control the direction by adjusting the min and max bearing
local bearingMax = 360;-- 1 and 360 is anywhere around, 90,180 would be anywhere below etc.
local minDepth = -300 --meters, negative

placeUnitRandomly(side, ship, distance, bearignMin, bearingMax, minDepth,true) -- call the function and pass in ALL the parameters
--placeUnitRandomly(side, ship, distance, bearignMin, bearingMax, minDepth) -- call the function leave out last param.
--placeUnitRandomly(side, ship, distance) -- call the function use defaults except for distance.
--placeUnitRandomly(side, ship) -- call the function leave out stuff let it use ALL defaults.
--placeUnitRandomly(side, ship, nil, bearignMin, bearingMax) -- call the function use defaults for some not others.
--placeUnitRandomly(side, ship, nil, nil, nil,nil ,true) --use defaults but enable random alt.


Only tested a few random facility types and ship\sub depths etc, seems to work pretty well though.
There are may be more facility sub-types beyond 4001 (sea bottom fixed) that I've not accounted for or come across yet.
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

Nice! wish I had seen this before making a 40 minute video on what I did, such is life. I like the hardening, didn't even think of that.

the Redo loop is weird, when I redid this a few minutes ago for a vid I just used a for loop, seemed much safer. If you screw up the redo count you can get in an infinite loop pretty easily. Not sure what the purpose of the redo loop is (goto I suppose is what it is?), I had copied that from someone elses random bios code.

Is there a reason to do the redo/goto loop instead of a regular for loop?

When I was making the video I was using a sub as an example and actually added code for random depth at the same time - funny that you did the same thing. Though in my video it was not pretty, went off the rails trying to do it on the fly while recording. Figure that is just as helpful and it is what it really looks like IRL.
User avatar
michaelm75au
Posts: 12467
Joined: Sat May 05, 2001 8:00 am
Location: Melbourne, Australia

RE: Function to randomly place a ship/sub at a new location

Post by michaelm75au »

Any manual loop like the 'goto' should always have a 'break-out' check to cater for a possible infinity loop.

I would use 'goto' if I didn't actually know ahead of time how often I needed to run the 'loop'; the loop might be based on a number of units that decrements by a variable amount each time thru the the loop.

But if I knew the 'loop' was to be run x times, then I would go with the more conventional 'while/for ... do' which makes the repeating block more visible to the coder.
Michael
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

thanks - makes sense.

Here is what I ended up with using a for loop:

-------
function placeShipRandomly(side,unit,distance,bMin,bMax,depth)
math.randomseed(os.time())
local u = ScenEdit_GetUnit({name=unit})
if u ~= nil then
for i = 1,20 do
local m = math.random(1,distance)
local b = math.random(bMin, bMax)
local point = ScenEdit_AddReferencePoint( {side=side, name="possible"..i, RelativeTo=unit, bearing=b ,distance=m})
ScenEdit_DeleteReferencePoint({side=side, name ="possible"..i})
local elevation = World_GetElevation({latitude = point.latitude, longitude= point.longitude})
print(elevation)
if elevation < depth then
u.latitude = point.latitude
u.longitude = point.longitude
return --exit, we mare done

end
end
print('no suitable location found, unit not moved')
else
print('unit does not exist')
end
end

placeShipRandomly('Blue','Group 106',155,1,359,-3010) -- call the function
------

and a video:

https://youtu.be/je6rl0YFQ_I
KnightHawk75
Posts: 1850
Joined: Thu Nov 15, 2018 7:24 pm

RE: Function to randomly place a ship/sub at a new location

Post by KnightHawk75 »

ORIGINAL: Whicker

Nice! wish I had seen this before making a 40 minute video on what I did, such is life. I like the hardening, didn't even think of that.

the Redo loop is weird, when I redid this a few minutes ago for a vid I just used a for loop, seemed much safer. If you screw up the redo count you can get in an infinite loop pretty easily. Not sure what the purpose of the redo loop is (goto I suppose is what it is?), I had copied that from someone elses random bios code.

Is there a reason to do the redo/goto loop instead of a regular for loop?

When I was making the video I was using a sub as an example and actually added code for random depth at the same time - funny that you did the same thing. Though in my video it was not pretty, went off the rails trying to do it on the fly while recording. Figure that is just as helpful and it is what it really looks like IRL.
Haha that is funny. Great minds. ;)

Yes I agree on ditching goto, when I saw the goto I also said why not use a for or while (but figured you were just trying to use different features of lua), but in tweaking it for my needs redoing that part wasn't my focus. I'll go back though refactor it with a 'while' + increment or a 'for' and post if you want, no biggy.

Have you found 20 enough? I ran across a case or two where 50 wasn't, but to do that I had to purposely try and break it with like a facility on small island surrounded by mostly water with high distance limit for it to exceed the limit, or a ship sitting in pearl harbor with small distance and degree limits.

Off to check out the video.

KnightHawk75
Posts: 1850
Joined: Thu Nov 15, 2018 7:24 pm

RE: Function to randomly place a ship/sub at a new location

Post by KnightHawk75 »

Updated for 'for' with 25 cap, I change to 'u' as well though I usually like descriptive vars.

Attachment file is just the same in .txt with formatting retained and extended doc\sample usage.

function placeUnitRandomly(side, ship, distance, bmin, bmax, mindepth,randomalt)
if (side == nil or side=='') or (ship == nil or ship =='') then
print('placeUnitRandomly() missing side or ship or unit name. Aborting call.');
return
end

if (bmin == nil or bmin < 0 or bmin > 360) then bmin = 1 end --if missing or invaid use 1 as default
if (bmax == nil or bmax < 0 or bmax > 360) then bmax = 360 end -- if missing or invalid use 360 as default
if (mindepth == nil or mindepth < -10000 or mindepth > 0) then mindepth = -2 end -- if missing or invalid use -2m default
if (distance == nil or distance < 1 or distance > 12000) then distance = 100 end -- if missing or invalid use 100nm default
randomalt = randomalt or false;
math.randomseed(os.time());

local u = ScenEdit_GetUnit({name=ship});
if u ~= nil then
for i = 1,25 do
local d = math.random(1,distance);
local b = math.random(bmin,bmax);
local point = ScenEdit_AddReferencePoint( {side=side, name='possible' .. tostring(i), RelativeTo=ship, bearing=b ,distance=d });
-- using addRP's ability to set the points bearing and distance relative to an existing unit as the new location for the unit
ScenEdit_DeleteReferencePoint ({side=side, name='possible' .. tostring(i)}); --should be ok to delete, just need the values
elevation = World_GetElevation({latitude=point.latitude, longitude=point.longitude}); -- get elevation of new RP to see if it is suitable
--print(elevation)
if u.type == 'Aircraft' then
--print('moving an aircraft')
u.latitude = point.latitude;
u.longitude = point.longitude;
if (randomalt) then
local ralt = math.random(305,10975.7); -- ~ 1000 to 36000 ft
u.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship, moveto=true,altitude=ralt}) --set desired alt to current.
end
return; --exit as we are done
elseif (u.type == 'Facility' and u.subtype ~= '4001') then
if (elevation > 0) then
-- facility that is not sosus bottom array? and needs to be above ground level; could be other subtypes to flag??.
--print('moving an non submerged facility')
u.latitude = point.latitude;
u.longitude = point.longitude;
return --exit as we are done only if elevation was > 0'
end
elseif (elevation < mindepth) then -- check if the new points depth is ok, if so assign the unit to the RPs lat/long
--print('moving an ship, sub or submerged facility')
u.latitude = point.latitude;
u.longitude = point.longitude;
if (randomalt and u.type == 'Submarine') then
if (elevation < -450 ) then elevation = -450 end; --cap max depth at like ~1475ft when it's much deeper.
if (elevation >= mindepth) then mindepth = -3 end; --reset min depth to like 10ft if elevation > min depth; change to 0 if want chance of surfaced subs.
local ralt = math.random(elevation,mindepth); --grab rando betweeen bottom and mindepth;
--print('changing altitude on ' .. ship .. ' to ' .. tostring(ralt) );
u.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship,moveto=true, depth=(ralt * -1)}); --set desired depth to current depth req postive
end
return; --exit as we are done
end
end
print ('unit was not able to find a suitable spot for placement, ship not moved'); -- if we got here then we've exceeded try count.
else
print("Unit does not exist");
end
--endfunc
end

User on your video page made a good\fair point, there is no need for the '.. i' to append the iteration number to the temporary RP name, I left it though.
Attachments
Func_place..Randomly.txt
(6.05 KiB) Downloaded 66 times
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

I left that comment, since its all about showing examples it is a good thing to show it I suppose, unless it gives the impression it is needed. No big deal.

If it can't find a proper new home after 20-30 loops then I think it is best to just exit and leave it where it is.

Was thinking this same code would be a good replacement for the random bios code that uses sets of lats and longs - I have trouble sometimes figuring those out. Would be easier to create one bio, then do this same code to make a bunch more. Then add code to assign them to a bios mission and random speed as well as depth.

Same thing for random merchants as well. Even air liners. Set random home bases and rtb.
User avatar
Gunner98
Posts: 6003
Joined: Fri Apr 29, 2005 12:49 am
Location: The Great White North!
Contact:

RE: Function to randomly place a ship/sub at a new location

Post by Gunner98 »

OK I am trying this out and on my first run it works brilliantly --Thank you

Question:

trying to set up a number of units to random locations at start each with a command something like:

placeUnitRandomly('NATO','F 210 FGS Emden', 40, 300, 30, minDepth,true)

Doesn't seem to work for me. The console error is:

placeUnitRandomly('NATO','F 210 FGS Emden', 40, 300, 30, minDepth,true)-- call the function and pass in ALL the parameters
ERROR: [string "Console"]:18: bad argument #2 to 'random' (interval is empty)

I'm using the text from post #7 and line 18 is: local b = math.random(bmin,bmax);

thanks

B

Thanks
Check out our novel, Northern Fury: H-Hour!: http://northernfury.us/
And our blog: http://northernfury.us/blog/post2/
Twitter: @NorthernFury94 or Facebook https://www.facebook.com/northernfury/
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

I think cause your bMin is larger than bMax? so it is trying to be math.random(300,30) which I don't think is valid.

try placeUnitRandomly('NATO','F 210 FGS Emden', 40, 30, 300, minDepth,true)

guess it needs a check for that too! it does get confusing with all the arguments.
User avatar
Gunner98
Posts: 6003
Joined: Fri Apr 29, 2005 12:49 am
Location: The Great White North!
Contact:

RE: Function to randomly place a ship/sub at a new location

Post by Gunner98 »

OK that worked - thank you.

Only issue is randomizing a unit generally north you will need to stick with NW or NE, certainly workable. Thanks.

One other quick question.

For AC I think it is the same except:

placeUnitRandomly('NATO','aircraft', 40, 30, 300, minDepth,false)


is that right? Testing seems to work either way but I'm working along a coastline so it may be messing things up


Thanks
Check out our novel, Northern Fury: H-Hour!: http://northernfury.us/
And our blog: http://northernfury.us/blog/post2/
Twitter: @NorthernFury94 or Facebook https://www.facebook.com/northernfury/
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

Only issue is randomizing a unit generally north you will need to stick with NW or NE, certainly workable. Thanks.

ah, I see, didn't think of that use case. That's a good one.

For the AC if you pass in True at the end then it uses a random alt between 1000 to 36000 ft. If you do false then it just stays the same as it was before. I think for AC you could also just do:
placeUnitRandomly('NATO','aircraft', 40, 30, 300) and skip the last 2 but I haven't checked that.
KnightHawk75
Posts: 1850
Joined: Thu Nov 15, 2018 7:24 pm

RE: Function to randomly place a ship/sub at a new location

Post by KnightHawk75 »

I didn't think of sanity checking that max < min, I can throw check in there for that and error, but I'd rather attempt to handle it. Let me ponder some ways to handle the 270 to 90 desire sort of arc input. hmm

Yes you should be able to it call without the additional params if you don't need them as in placeUnitRandomly('NATO','aircraft', 40, 30, 300)
It'll use defaults for those params which are -2 meters for minDepth for ships (ignored on others), and false is the default for using randomization of altitude\depth.
User avatar
Primarchx
Posts: 1954
Joined: Sun Jan 20, 2013 9:29 pm

RE: Function to randomly place a ship/sub at a new location

Post by Primarchx »

Watched your video. It was timely as I was just starting to play around with functions for my Desert Fox scenario. Thanks!
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

I added some code to KHs to allow northerly bearing - so bmin can be more than bmax - like 340,10

edited part of the code is:

local b
if bmin > bmax then --check if they want a bearing roughly north ex between 350 and 10
local angle = 360 - (bmin - bmax) --get actual angle of possibility
print(angle)
b = math.random(angle) + bmin -- random angle and then add back to bmin
--print(b)
if b > 360 then --if that goes over 360 then subtract 360
b = b - 360
end -- if b>360
else
b = math.random(bmin,bmax) --normal bmin and bmax, bmin < bmax
end --bmin > bmax check


full code below and attached
-----------------------------------------------------
-- Function to move unit semi randomly up to a limit of distance from start, in bearing of optional choosing
-- and to optionally set depth or altitude semi randomly
-- side: (string) side name of unit; REQUIRED
-- ship: (string) name of unit; REQUIRED
-- distance: (number) max nm distance to randomly try. 1-12000; default = 100
-- bmin: (number) min bearing to try from 1-360; default 1
-- bmax: (number) max bearing to try from 1-360; default 360
-- mindepth:(negative number) when searching for a location for a sub or ship apply this minimum -elevation check; default -2meters
-- randomalt: (boolean) defaults to false
--
-- To users:
-- Script function is primarly meant to be placed with other 'global' scripts in a scenario-onstartup\load event.
-- so that you run it once and use it everywhere, though technically speaking you can use it as a fragment.

function placeUnitRandomly(side, ship, distance, bmin, bmax, mindepth,randomalt)
if (side == nil or side=='') or (ship == nil or ship =='') then
print('placeUnitRandomly() missing side or ship or unit name. Aborting call.');
return
end

if (bmin == nil or bmin < 0 or bmin > 360) then bmin = 1 end --if missing or invaid use 1 as default
if (bmax == nil or bmax < 0 or bmax > 360) then bmax = 360 end -- if missing or invalid use 360 as default
if (mindepth == nil or mindepth < -10000 or mindepth > 0) then mindepth = -2 end -- if missing or invalid use -2m default
if (distance == nil or distance < 1 or distance > 12000) then distance = 100 end -- if missing or invalid use 100nm default
randomalt = randomalt or false;
math.randomseed(os.time());

local u = ScenEdit_GetUnit({name=ship});
if u ~= nil then
for i = 1,25 do
local d = math.random(1,distance);
local b
if bmin > bmax then --check if they want a bearing roughly north ex between 350 and 10
local angle = 360 - (bmin - bmax) --get actual angle of possiblity
print(angle)
b = math.random(angle) + bmin -- random angle and then add back to bmin
--print(b)
if b > 360 then --if that goes over 360 then subtract 360
b = b - 360
end -- if b>360
else
b = math.random(bmin,bmax) --normal bmin and bmax, bmin < bmax
end --bmin > bmax check
--print(b)
local point = ScenEdit_AddReferencePoint( {side=side, name='possible' .. tostring(i), RelativeTo=ship, bearing=b ,distance=d });
-- using addRP's ability to set the points bearing and distance relative to an existing unit as the new location for the unit
ScenEdit_DeleteReferencePoint ({side=side, name='possible' .. tostring(i)}); --should be ok to delete, just need the values
elevation = World_GetElevation({latitude=point.latitude, longitude=point.longitude}); -- get elevation of new RP to see if it is suitable
--print(elevation)
if u.type == 'Aircraft' then
--print('moving an aircraft')
u.latitude = point.latitude;
u.longitude = point.longitude;
if (randomalt) then
local ralt = math.random(305,10975.7); -- ~ 1000 to 36000 ft
u.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship, moveto=true,altitude=ralt}) --set desired alt to current.
end
return; --exit as we are done
elseif (u.type == 'Facility' and u.subtype ~= '4001') then
if (elevation > 0) then
-- facility that is not sosus bottom array? and needs to be above ground level; could be other subtypes to flag??.
--print('moving an non submerged facility')
u.latitude = point.latitude;
u.longitude = point.longitude;
return --exit as we are done only if elevation was > 0'
end
elseif (elevation < mindepth) then -- check if the new points depth is ok, if so assign the unit to the RPs lat/long
--print('moving an ship, sub or submerged facility')
u.latitude = point.latitude;
u.longitude = point.longitude;
if (randomalt and u.type == 'Submarine') then
if (elevation < -450 ) then elevation = -450 end; --cap max depth at like ~1475ft when it's much deeper.
if (elevation >= mindepth) then mindepth = -3 end; --reset min depth to like 10ft if elevation > min depth; change to 0 if want chance of surfaced subs.
local ralt = math.random(elevation,mindepth); --grab rando betweeen bottom and mindepth;
--print('changing altitude on ' .. ship .. ' to ' .. tostring(ralt) );
u.altitude = ralt; --set alt
ScenEdit_SetUnit({side=side, unitname=ship,moveto=true, depth=(ralt * -1)}); --set desired depth to current depth req postive
end
return; --exit as we are done
end
end
print ('unit was not able to find a suitable spot for placement, ship not moved'); -- if we got here then we've exceeded try count.
else
print("Unit does not exist");
end
--endfunc
end


local side = 'Biologics';
--local ship = 'A-100 Premier [Il-476]' --can be group or individual ship or sub aircraft;
--local ship = 'SSN 774 Virginia [Flight I]'; --sub max depth ~1475
--local ship = 'Bottom Fixed Array (SOSUS)'; facility subtype 4001;
--local ship = 'DDG 96 Bainbridge [Arleigh Burke Flight IIA]'; --ship
local ship = '012 Rais Hadj Mubarek [PL-877EKM Kilo]'
--local ship = 'Flight 18'; --group of 2 a-100 aircraft

local distance = 150; -- max distance in miles away from starting point
local bearignMin = 330; -- you can control the direction by adjusting the min and max bearing
local bearingMax = 50;-- 1 and 360 is anywhere around, 90,180 would be anywhere below, 350,10 would be northerly
local minDepth = -40 --meters, negative

placeUnitRandomly(side, ship, distance, bearignMin, bearingMax, minDepth,true) -- call the function and pass in ALL the parameters
--placeUnitRandomly(side, ship, distance, bearignMin, bearingMax, minDepth) -- call the function leave out last param.
--placeUnitRandomly(side, ship, distance) -- call the function use defaults except for distance.
--placeUnitRandomly(side, ship) -- call the function leave out stuff let it use ALL defaults.
--placeUnitRandomly(side, ship, nil, bearignMin, bearingMax) -- call the function use defaults for some not others.
--placeUnitRandomly(side, ship, nil, nil, nil,nil ,true) --use defaults but enable random alt.

-----------------------------------------------------
Attachments
luaplace..randomly.txt
(6.63 KiB) Downloaded 69 times
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

when searching for a location for a sub or ship apply this minimum -elevation check; default -2meters

I think the default should be more like -40m. once you get in shallow water there are too many path issues.

I'm going to add this into my starter scen as a built in script, I'll change it there.
User avatar
Gunner98
Posts: 6003
Joined: Fri Apr 29, 2005 12:49 am
Location: The Great White North!
Contact:

RE: Function to randomly place a ship/sub at a new location

Post by Gunner98 »

Thank you, I'll include the updated script when I update the scenario next. You guys are fast.
Check out our novel, Northern Fury: H-Hour!: http://northernfury.us/
And our blog: http://northernfury.us/blog/post2/
Twitter: @NorthernFury94 or Facebook https://www.facebook.com/northernfury/
KnightHawk75
Posts: 1850
Joined: Thu Nov 15, 2018 7:24 pm

RE: Function to randomly place a ship/sub at a new location

Post by KnightHawk75 »

Sweet change I'll update my local copies, nice work.

On the default i guess it depends on what person wants. I was using -10m (-33ft) for while before lower it to -2 during testing (wanting to get some close to shore around a harbor area) and that's the amount also used when elevation > minDepth for a sub or ship, probably right that -2 is two low as some sort of safe standard due to shoreline path glitching but -40m (120+ft) might be a little high, I'll put my local copy back to -10m but to each their own you know. ;)
User avatar
Gunner98
Posts: 6003
Joined: Fri Apr 29, 2005 12:49 am
Location: The Great White North!
Contact:

RE: Function to randomly place a ship/sub at a new location

Post by Gunner98 »

Running this function for a bunch of land units using GUIDs

placeUnitRandomly(Syria, guid='92685ebe-0dc5-42e0-b9a7-86b7ff498175')

getting a syntax error - probably something silly. Any ideas?


placeUnitRandomly(Syria, guid='92685ebe-0dc5-42e0-b9a7-86b7ff498175')
ERROR: [string "Console"]:112: ')' expected near '='

adding brackets:

placeUnitRandomly(Syria, ship=(guid='92685ebe-0dc5-42e0-b9a7-86b7ff498175'))
ERROR: [string "Console"]:112: ')' expected near '='


Check out our novel, Northern Fury: H-Hour!: http://northernfury.us/
And our blog: http://northernfury.us/blog/post2/
Twitter: @NorthernFury94 or Facebook https://www.facebook.com/northernfury/
Whicker
Posts: 665
Joined: Tue Jun 19, 2018 9:54 pm

RE: Function to randomly place a ship/sub at a new location

Post by Whicker »

I think you are supposed to use the unit name not the guid. Should just be placeUnitRandomly(side, ship) so placeUnitRandomly('Syria', 'myUnitsName')

and if you are passing in the names directly rather than using a variable you have to enclose them in quotes as they are strings. if you have a bunch of land units and they share the same name I am not sure what would happen.
Post Reply

Return to “Lua Legion”