Say you have a gameobject that is at a certain position(this could be your player).

Now say that you have a melee NPC that has to be within a certain range to hit the Player.

Now you would do something like this to find out where the player is:

var targetPosition = target.transform.position;

Say that the range of the NPC is 4 meaning he can be 4 units away from the player before he can start attacking him.

My question is how would you subtract that to get a position that is within range?

And am i doing this type of thing correctly? or is there a better way of doing it? :)

Any help would be appriciated a lot!


Use Vector3.Distance to get the distance between two positions.

float distanceToTarget = Vector3.Distance(playerPosition, targetPosition);
float distanceThreshold = 4f;
if (distanceToTarget <= distanceThreshold) {
    // Attack
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.