Getting a Vector3 value closest x studs away from a position?

  1. As we all know in most games when NPC’s move to you they take the shortest route possible. I’d like to do this as well.

  2. The issue is I’m having trouble getting this position the NPC should move to; some have said: “Loop until and use :MoveTo() until you are x studs away from the target”. Which isn’t a bad idea but there are some problems:

  1. I’m using Pathfinding
  2. I want to keep the system as resource-friendly as possible

Another solution some have presented is doing something like so: Humanoid:MoveTo(Target.Position + Vector3.new(x,0,0)) or x on the Z Axis. which isn’t necessarily good since it’s always going to be on that axis. My goal is just to get the NPC to move to x studs away from the target (obviously taking the shortest route).

Lastly, someone has also suggested to generate the position randomly with an x offset but then again If the target is in front of you I don’t want the NPC to move behind the target.

I hope I can get some good information out of this.

2 Likes

It sounds like your question is fairly simple of an answer, and you have a solid enough understanding that you might be overthinking it.

You can use Vector3.unit to easily calculate a new Vector3 with an offset of a specific number of studs in a specific direction. Here is a super simple concept piece that would create a new Vector3 value 5 studs away from the target:

local currentPos = Vector3.new(100,0,0)
local targetPos = Vector3.new(0,0,0)
local keepDistance = 5
local newPos = targetPos + ((currentPos-targetPos).Unit * keepDistance)
4 Likes

Would this be the closest distance? And could you tell me more about Vector3.Unit as I don’t normally look into Vectors much.

Yes, this code specifically generates a Vector3 that is “5 studs away from targetPos, in the direction of currentPos.”

Vector3.Unit creates a normalized vector. Normalized means it’s magnitude is 1 (the length of the line it would make if where where to draw a triangle from 0,0,0 to the new vector it made). This is super useful to use a directional vector.

Basically, currentPos-targetPos returns a vector representing the difference in the two positions, when we normalize it with .Unit to get the direction from the target pointing at the current.

1 Like

Is there a way to keep a constant distance instead of making it so its keepDistance or smaller then keepDistance

1 Like

The example I posted does just that. In my example the new Vector3 (newPos) will always be 5 studs (keepDistance) away from the target at time of calculation.

If you wanted something to only move when greater then or less then the distance you’d want to use Vector3.Magnitude, but my example accomplishes what you are asking about.

1 Like

Understood. Made the small mistake of doing

targetPos + ((currentPos-targetPos).Unit * keepDistance)

when I actually wanted

currentPos + ((currentPos-targetPos).Unit * keepDistance)

Anyway got what I need thx