How To Move A Vector3 Towards Another Vector3

My goal is to move a Vector3 towards another Vector3, both have unknown values of course, but the increment I want to define. For instance, moving one Vector3 1 stud forwards and towards another Vector3.

Using CFrame is easy;

local A = workspace.PartA
local B = workspace.PartB

--// A self explanatory CFrame, setup to increment towards PartB
local CFrameThatIsAtPartAThatFacesPartB = CFrame.new(A.Position,B.Position)

--// I can then move it towards PartB using a simple CFrame application
CFrameThatIsAtPartAThatFacesPartB *= CFrame.new(0,0,-1)

A.CFrame = CFrameThatIsAtPartAThatFacesPartB
--// Moves 1 stud forwards to PartB

Not sure how to do it with only Vector3;


--// Trying to do the same but limited to Vector3

local IncrementCloserToPartB = Vector3.new(1,1,1)

A.Position += Vector3.new(1,1,1) --// Move closer to PartB by an increment of 1,1,1 studs

--// OR

local ExpanseDifferenceBetweenTheTwo = A.Position-B.Position

A.Position += ExpanseDifferenceBetweenTheTwo 

--// Doesn't actually work but it's essentially what I'm trying to do

You were on the right track with subtracting the vectors from each other!
Subtract the vector you want to “move” from the one you want it to get closer to, and then unitize the result to get what direction you need to move in. Then from there, it’s straightforward.

local direction = (B.Position - A.Position).Unit
A.Position += direction * STUDS_AMOUNT  -- translates A towards B by STUDS_AMOUNT
1 Like

Why not just use Vector3:lerp()?

A.Position = A.Position:Lerp(B.Position, number)
1 Like

Lerp is very useful but AFAIK it wouldn’t be the optimal choice for my use case. As it applies a multiplicative difference instead of a flat number. I don’t think you can reliably apply a pre-defined Vector3 increment like 1,1,1 in this case via Lerp. Correct me if I’m wrong though!

@Great_Bird provided the perfect solution! Thank you! :smiley:

1 Like

This works, but it will overshoot if STUDS_AMOUNT is greater than the distance from A to B. Here’s a version that deals with that:

function moveVectorTowards(start: Vector3, goal: Vector3, distance: number): Vector3
    if distance >= (goal - start).Magnitude then return goal end
    return start + (goal - start).Unit * distance
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.