Jump to content
Sign in to follow this  
grollig

Finding the closest of two directions for spawned vehicle on road

Recommended Posts

Hi there,

 

I'm currently working on a script that will do the following:

 

1. Spawn a vehicle at a random position on a road (solved with SHK_Pos)

2. Add a crew to the vehicle

3. Order the crew to drive to a certain position (_centerPos)

 

All this is working fine*, but there is still a 50/50 chance the spawned vehicle on the road will face the wrong direction (away from the desired destination).

As a result, the AI will try to turn the vehicle, sometimes crashing into obstacles at the edge of the road.

So I'd like to have the vehicle facing the proper direction right after the spawn.

 

Here's the part of the script where I am stuck:

// spawn the vehicle
_veh = _vehType createVehicle _vehSpawnPos;
 
// get the roadsegments near the vehicle's spawnposition
_nearRoads = _vehSpawnPos nearRoads 10;
 
// select the roadsegment closest to the vehicle
_road = _nearRoads select 0;
 
// get the next connected roadsegements to determine the direction of the road
_roadConnectedTo = roadsConnectedTo _road;
_connectedRoad = _roadConnectedTo select 0;
_roadDirection = [_road, _connectedRoad] call BIS_fnc_DirTo;
 
// get the direction from the vehicle to its destination
_vehDestinationDir = [_vehSpawnPos, _centerPos] call BIS_fnc_dirTo;
 
// This part has to be solved:
// check if the variable _roadDirection holds the best of two road directions leading to the destination
// if so, turn the vehicle to _roadDirection, else turn the vehicle around by 180 degrees

* Big thanks to Shuko for his great SHK_Pos functions and arjay for sharing his solution to the problem with parallel orientation of a spawned vehicle on a road

Share this post


Link to post
Share on other sites

Instead of

_connectedRoad = _roadConnectedTo select 0;

check which road segment is closer to your target and choose that one. That's still not the ideal solution as the closest way to the destination may start by first going further away from it but it should be pretty rare.

 

Edit:

if (((_roadConnectedTo select 0) distance _centerPos) < ((_roadConnectedTo select 1) distance _centerPos)) then {
_connectedRoad = _roadConnectedTo select 0} else {
_connectedRoad = _roadConnectedTo select 1};

should work unless you place the car on a crossroads.

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
Sign in to follow this  

×