I’ve run into a very strange issue that suggests that I don’t yet fully understand how unity works internally, and would welcome any insight on what I got wrong.
Here’s what I’m trying to do: I have an object that I want to move in the direction that it is facing (i.e. in the direction of the transform’s ‘forward’ vector).
Here is what does NOT work but, which I thought should work (see below for what happens):
transform.Translate(transform.forward * Time.deltaTime); // translate in Forward direction
This, on the other hand, works:
transform.position = transform.position + transform.forward * Time.deltaTime;
To my uneducated mind, above two lines should have the same effect: move the object’s origin by deltaTime’s fraction of the object’s forward vector in the direction of said vector.
Using an object (no parents) with a rotation of 0,0,0 the two above code lines are exactly equivalent. So far, so good.
HOWEVER, when I cange the object’s y rotation with Editor’s Inspector, the line that uses “Translate()” results in a movement direction that is EXACTLY TWICE the amount of Y rotation, i.e. the object moves
- ‘backwards’ (180 degrees) when it should move right (90 degrees),
- ‘forward’ (0 = 360 degrees) when it should move back (180 degrees), and
- right (90 degrees) when it should move ‘ahead and right’ (45 degrees).
I only use Editor to change the object’s heading, no code at all to set any rotation in C#.
So it looks as if the ‘forward’ vector is interpreted different from how I do in Translate().
So obviously, I’m not fully understanding how transform.Translate() is supposed to work. Can someone please point out what I got wrong? This is driving me nuts. The only explanation that I can think of is that Translate() takes a directional vector (in this case ‘forward’), and applies it’s internal roation to the vector before performing the translation, i.e. making the translation direction local-relative. This would account for the double rotation - but clashes with how I expect a translation to work.
Thanks,
-ch