- Home /
Difference between moving forward with transform.Translate vs transform.localPosition
I'm working on a simple 4x4 grid based game and am coding the scripts in C#. When I implement either of these lines of code they appear to have the same effect, I don't have them both running at the same time.
transform.Translate(Vector3.forward*Time.deltaTime*6f);
transform.localPosition += transform.forward*Time.deltaTime*6f;
I was wondering if there was a significant difference between the two or if I should use one over the other, thanks!
Correct me if I'm wrong, but isn't localPosition
is just a property with it's setter
as Translate
?
Not exactly - the Translate takes in to consideration the rotation of the object and applies that to the vector before adding it.
actually, you can set the space in which Translate
moves. If you use Space.Local
(or something like that) then transform.localPosition
is defined as:
function set localPosition(value:Vector3) {
this.Translate(value, Space.Local);
}
I think. It might be the other way around
No not really - because altering localPosition with a vector does not rotate that vector based on localRotation.
Put an object in a scene, rotate it so that it is at 0,90,0 then:
transform.localPosition += Vector3.forward;
Is not the same as
transform.Translate(Vector3.forward);
Answer by whydoidoit · Oct 16, 2013 at 12:50 AM
Well I always use the second format, they are indeed exactly the same presuming that there is no parent.
Translate takes into consideration the rotation of the local object, so it converts Vector3.forward into the direction of the current object.
To get exactly the same effect with or without parents, you would need to do:
transform.position += transform.forward * ....
Bear in $$anonymous$$d that it is marginally faster to work with localPosition compared to position - especially when the object has parents.
Answer by vexe · Jun 19, 2014 at 04:57 PM
This is what Translate
literally does:
public void Translate(Vector3 translation, [DefaultValue("Space.Self")] Space relativeTo)
{
if (relativeTo == Space.World)
{
this.position += translation;
}
else
{
this.position += this.TransformDirection(translation);
}
}
I really believe one's decompiling and taking a peek himself is very educational. Have doubt how XXX work? just take a look...
I use ILSpy, it served me well.
It might sound intimidating but the process goes something like this:
Download and install ILSpy.
Drag/drop the UnityEditor.dll located in the Editor/Data/Managed folder in your disk to ILSpy
Browse through, lurk around till you find what you're looking for.