- Home /
How to move a object forward relative to it smoothly without update function?
I want the player to move 1.5 units forward relative to himself but with the script i have it moves only in global z axis and not relative to him.
function MovePlayer(){
moving = true;
var start = GameObject.FindWithTag("PlayerController").transform.position;
var end = start + vecotr3(0,0,1.5);
var speed = 1;
for (var t: float = 0; t < 1;){
t += Time.deltaTime * speed;
GameObject.FindWithTag("PlayerController").transform.position = Vector3.Lerp(start, end, t);
yield;
}
moving = false;
}
I want player to move relative to him and not global.
Answer by Dave-Carlile · Dec 14, 2012 at 01:48 PM
When you calculate your end vector you're doing it using world coordinates, which is why it moves in world space and not relative to the player. You need to transform the coordinates so they're in player, or object space. Unity does much of this work for you in this case. The Transform class has vectors for forward, right, left, and so on. These point in the proper direction depending on how the object is rotated.
If you want to move the object forward 1.5 units then you can calculate the starting and ending position like this:
var transform = GameObject.FindWithTag("PlayerController").transform;
var start = transform.position;
var end = start + transform.forward * 1.5;
The forward vector is unit length, meaning it's pointing in the object's forward direction to a point 1 unit away. You can multiply the vector by any value to give it that length, so multiplying it by 1.5 will give you a point 1.5 units away, or multiplying it by 20 will give you the point 20 units away.
Glad to help. Please accept this as the answer if it worked for you, so the question and answer can help others if they run across the same issue.