- Home /
Translate not working properly
My problem seems easy, but I'm 3hrs trying to resolve... Let's go:
In my scene I have a Cube and a script (called Cube.cs) in C#.
All I want to do is rotate and translate the cube, in Cube.cs I have:
//
transform.eulerAngles = new Vector3(-30f, 0f, 0f); //OK
transform.Translate(Vector3.forward * 3f); //here is the problem
//
What's happening:
//
After the rotation, when I do the Translate, the Cube (GameObject) does not move 3 units, but 2.52..., if I not rotate the cube then the cube Translate right, but when I rotate the cube the cube not translate the 3 units. I appreciate all help to solve this.
Are you sure? Try printing the distance between the start and end points to console.
Vector3 start = transform.position;
transform.eulerAngles = new Vector3(-30f, 0f, 0f); //O$$anonymous$$
transform.Translate(Vector3.forward * 3f); //here is the problem
Debug.Log(Vector3.Distance(start , transform.position));
Are you sure there's nothing else influencing your object? This works fine:
using UnityEngine;
public class $$anonymous$$oveSome : $$anonymous$$onoBehaviour {
void Awake () {
Vector3 previous = this.transform.position;
transform.eulerAngles = new Vector3(-30f, 0f, 0f);
transform.Translate(Vector3.forward * 3f);
Debug.LogFormat ("I moved {0} units", (this.transform.position - previous).magnitude);
}
}
I think you're reading the object's position as Z = 2.598
, but the Y = 1.5
. That is a total of 3 units.
Yes, I didn’t realize that translating (locally) after rotation, the units translated were affected by the rotation. I need to find a way to move in Z all the 3 units. Thanks for the answer.
heyy godoy! can i know how u solved that issue? because i m facing with the same issue too
Answer by FlaSh-G · May 08, 2018 at 09:24 PM
Transform.Translate, if not told otherwise, translates the object along the local axes. Imagine your cube had a face drawn on the front side. transform.Translate(Vector3.forward);
will always move in the direction of that face, no matter where that face points at. So your code does move 3 meters, but not 3 meters in the Z direction. Since you rotated it, the cube will move a bit along the Y axis too.
If you want the cube to move along the Z axis no matter where it's pointing at, you have to specify the optional Parameter for Transform.Translate.
transform.Translate(Vector3.forward * 3f, Space.World);
Thank you, I see the "problem" now, my mistake. Now I need to find a way to put the gameobject 3 units away in z-axis. I'm going to try the commutative transformations to solve this.
Your answer
Follow this Question
Related Questions
Moving and rotating a ball 0 Answers
Mesh has rotation/translation when imported 1 Answer