- Home /
Math Question: Get EnemyObject to NavMeshDestination x Units from Player
Math is not my strong suit.
I have an enemy and a player, and I want the enemy (an archer), to set the NavMesh Destination to be x units from the player, in the same angle between the player and enemy. So if the enemy is further than X units, they will move forward. If the enemy is closer than X units, they will move back.
For the life of me I can't seem to figure this out. probably because math is hard :)
Anyone know the solution?
Here is my latest math, which isn't working. The intent is that if the enemy needs to move forward, the navmesh destination should be set to "forward" etc. But it doesn't seem to work. :/
if ((distanceToPlayer > (shootRange + 1)) || (distanceToPlayer < (shootRange - 1)))
{
var positionFromPlayer : Vector3; // Final position to set navmesh Destination to
var distanceTo$$anonymous$$ove = (distanceToPlayer - shootRange); // The number of units distance between the enemy (this) and shoot range
if (distanceTo$$anonymous$$ove > 0) // If enemy needs to move forward
{
positionFromPlayer = (transform.position + Vector3.forward);
enemyNav.SetDestination(positionFromPlayer);
}
else // If enemy needs to move back
{
positionFromPlayer = (transform.position + Vector3.back);
enemyNav.SetDestination(positionFromPlayer);
}
}
Answer by infinitypbr · Jun 23, 2013 at 04:27 AM
var positionFromPlayer : Vector3;
var distanceToMove = (distanceToPlayer - shootRange);
if (distanceToMove > 0)
{
positionFromPlayer = (transform.position + transform.forward);
enemyNav.SetDestination(positionFromPlayer);
}
else
{
positionFromPlayer = (transform.position - transform.forward);
enemyNav.SetDestination(positionFromPlayer);
}
This works. Ensure that the navMesh stopping distance is set to zero, of course. Or zed, whichever you prefer. It's not as elegant as my initial choice, but it works.
Your answer
Follow this Question
Related Questions
Set the speed of an object by its distance with another object 1 Answer
How to get the distance between two objects in feet/meter? 1 Answer
Make a navmesh object start moving in a circle around an object 0 Answers
How to make this script find distance inside radius? 1 Answer
Check Radius Problem 2 Answers