- Home /
Maintain direction regardless of rotation
Hey there! So, I am attempting to control my player on the X axis, with the left and right keys, which works thus far. I am then trying to layer on some rotational functionality, whereupon the player character 'leans' left or right dependant on movement. I have also been able to achieve this.
However, my issue arises when the player character successfully leans in to its movement but then subsequently moves in that new direction. See figure for example.
The blue square represents my player character at a standstill. While the red square represents what currently happens when it leans in to its movement. Lastly the green square represents how I would like it to act.
Here is my code thus far.
#pragma strict
var playerSpeed = 10.0;
var playerRotation = -5;
function Start () {}
function Update ()
{
var movementX = Input.GetAxis("Horizontal") * Time.deltaTime * playerSpeed;
var rotationZ = Input.GetAxis("Horizontal") * playerRotation;
transform.Translate(movementX, 0, 0); //dictates the movementX variables direction. In this case, obviously the X axis.
transform.localRotation = Quaternion.Euler(0,0,rotationZ);
}
Answer by Eric5h5 · Jul 17, 2012 at 07:31 AM
Use Space.World in Translate. (Another possibility: make an empty object that's used as the transform which is controlled by the player, with the visible object as a child of the empty object. The child would be rotated but not the parent.)
transform.Translate(movementX, 0, 0, Space.World);
Worked perfectly! Hopefully that is how you intended me to implement it. One thing that is curious, of which I am unsure if it matters.
When I move left it shows a rotational value of 5 on the Z axis, and when I move right it shows a rotational value of 355 on the Z axis.
Thank you so much for your help!!
Upon further reflection I am guessing that it has to do with the fact that I am multiplying the Input.GetAxis by the playerRotation. Other than the values being really high, do you think this will effect performance at all?
It's just a multiplication, so it would have nearly zero effect on performance. You'd need to do millions of multiplications to get anything measurable.
Ah!! Thank you so much! :P Obviously I am entirely new to program$$anonymous$$g and Unity. You have helped immensely!
Also, if you, or anyone else is curious. Fruits of said labour.