- Home /
fixed distance for Vector3.moveTowards ?
What I am trying to find out is, if there is a way to create a preset distance for the Vector3.moveTowards statement.
Meaning instead of something like
transform.position = Vector3.MoveTowards(transform.position, target.position, speed);
If it is possible to do something like
transform.position = Vector3.MoveTowards(transform.position, 20 in x-direction, speed);
Meaning instead of a target.position, use a fixed distance instead. And if not, if there is a possible work-around for it.
Answer by robusto · Jun 14, 2014 at 10:33 AM
This is what Vector3.MoveTowards essential does:
Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta)
{
Vector3 diff = target - current;
float mag = diff.magnitude;
if( mag < maxDistanceDelta )
return current;
diff.Normalize();
return (maxDistanceDelta * diff) + current;
}
If you want it to move only on the x component you need to make the y and z components the same as your position so this function doesn't move it closer to those y and z values since they are already there.
Vector3 newTargetPos = target.position;
newTargetPos.y = transform.position.y;
newTargetPos.z = transform.position.z;
transform.position = Vector3.MoveTowards(transform.position, newTargetPos, speed);
The var speed (maxDistanceDelta) controls how big/small of a step you take in that direction everytime you call MoveTowards.
That would work for the y- and z-axis, though how do I set the newTargetPos x-axis? I mean, I want it to move by a fixed value from whereever the current position is. Something like, whereever the object is on the x-axis, make it move further by 20.
Global:
transform.position += Vector3.right * 20f; // or -20f to move left
Local:
transform.position += transform.right * 20f; // or -20f to move left