I’ve got a small problem trying to do a very simple random roaming script for a top down game.
My object should move forward, then every second rotate a bit, but continue to move where is facing.
The script is on an empty GameObject which is father to my mesh.
It goes like that:
#pragma strict
var speed:float=3;
var changeDir:float=1;
private var timer: float;
function Start()
{
timer = changeDir;
}
function Update() {
transform.Translate(transform.forward * Time.deltaTime * speed);
if (timer>0)
timer-=Time.deltaTime;
else
{
transform.RotateAround(transform.position, Vector3.up, 10);
timer = changeDir;
}
}
the problem is the facing direction doesn’t look to be in sync with the rotation: my object changes the movement direction, but it doesn’t go towards where it’s facing. So it ends doing all the strangest things (like walking backwards).
Well, shouldn’t be more correct, in my code, to use transform, then? Since I’m rotating the character, shouldn’t the forward direction be relative to the player rather than to the world?
[Sorry if this seems stupid, I really need to understand how the transforms work]
Well, transform.Translate works a bit different than if you mess directly with positions.
By default is will convert the translation parameter to Local space, unless otherwise specified.
From the documentation
function Update() {
// Move the object forward along its z axis 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);
// Move the object upward in world space 1 unit/second.
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
transform.Translate(Vector3.forward * Time.deltaTime);
// should be equal to
transform.position = transform.position + transform.forward * Time.deltaTime;
// or
transform.position = transform.position + transform.TransformDirection(Vector3.forward) * Time.deltaTime;
...
transform.Translate(Vector3.forward * Time.deltaTime, Space.World);
// should be equal to the one above
transform.position = transform.position + Vector3.forward * Time.deltaTime;
The Translate method is just here to make it easier for people, as it will do the world to local space translations for you.