- Home /
Moving a model relative to one axis
Hello, first time using unity, so i'm a little confused as to how to do this...
I have a jet/spaceship type thing, which needs to move relative to its facing (y axis I think) and when a direction is pressed, it should rotate its facing, move that direction, and also tilt along its x axis to give the impression of banking. I have the turning and moving at an angle working fine, but when I try to add the tilt, everything goes to pot, and it has a fit when the keys are pressed. Here's my code:
void Update ()
{
float rotationAmount = Input.GetAxis ("Horizontal") * turnSpeed * Time.deltaTime;
transform.Rotate(0,0,rotationAmount);
float moveAmount = Input.GetAxis ("Vertical") * moveSpeed * Time.deltaTime;
rigidbody.AddRelativeForce(-moveAmount,0,0);
if(Input.GetAxis ("Horizontal") == 1)
{
transform.eulerAngles = new Vector3(270 - 45,0,transform.eulerAngles.z);
}
else if(Input.GetAxis ("Horizontal") == -1)
{
transform.eulerAngles = new Vector3(270 + 45,0,transform.eulerAngles.z);
}
else
{
transform.eulerAngles = new Vector3(270,0,transform.eulerAngles.z);
}
}
Answer by Ranger-Ori · Jul 24, 2012 at 07:33 AM
transform.eulerAngles = new Vector3(270 - 45,0,transform.eulerAngles.z);
You do realize that you change the settings of vectors x,0,z. I think z axis might also become affect of this change.
If you want to change only the x axis, then your code should look like this:
transform.eulerAngles.x = 270 - 45; //which you can write just 225.
And you should try using localEulerAngles, in case you have a parent obj.
The reason I didn't just set x to the value, is that i'm writing in C# which needs the whole vector3, the x,y and z are read-only. And the model should always have a y rotation of 0, and x is just kept the same. Using localEulerAngles has fixed it though.