How can I set an object's bodyvelocity so it moves towards a set point?
So let's say I want a part to move from its spot at (0,0,0) to (10,0,1) with BodyVelocity. I insert it into the part. And the velocity of that part would be ?
This is a simple vector problem. Using vector subtraction, you can derive the vector pointing from one vector to another vector.
pointingVector = endVector - startVector
where pointingVector
is the vector pointing from startVector
to endVector
. This will be the direction of your velocity vector.
The magnitude of a velocity vector describes its speed. We know this because speed is defined to be the square root of the dot product of a velocity vector and itself. If we want a velocity to be a certain speed, we would first make it a unit vector by dividing the vector by its own magnitude and then multiplying it by the target speed. We can use the .unit
property to make a vector a unit vector without the division.
Taking the above, setting the velocity of a part moving from (0, 0, 0) to (10, 0, 1) would look like the code below, assuming bodyVelocity
references the BodyVelocity object.
local startPosition = Vector3.new(0, 0, 0) local endPosition = Vector3.new(10, 0, 1) local targetSpeed = 50 bodyVelocity.velocity = targetSpeed*(endPosition - startPosition).unit