# Move and Rotate on a fixed axis?

Hello all.

I’m working on a 2D game. The player controlled object is movable left and right on the X axis. I have also set it up that the rotation on the X axis is controlled via “Mouse X” movement.

What I want, is for the object to be locked on the X axis while being able to move and rotate at the same time. Currently, if I move after I rotate at all, the object moves off in the direction that it’s rotated to.

I also need the object to have movement restrictions, so that you can’t move it off screen (playing on a fixed 2d plain) and the rotation should be limited to certain angles.

Here is my basic code at the moment.

``````var HorizontalSpeed : float = 2.0;

function Update () {

var v : float = HorizontalSpeed * Input.GetAxis ("Mouse X");
var horiz : float = Input.GetAxis("Horizontal");

transform.Translate(Vector3(horiz,0,0));
transform.Rotate ( 0, v, 0);

}
``````

Any help would be greatly appreciated!

Paul

By default, transform.Translate() (and Rotate(), too) modify the local space, not the world space. So instead you should use:

``````transform.Translate(Vector3(horiz,0,0),Space.World);
``````

http://unity3d.com/support/documentation/ScriptReference/Transform.Translate.html

On the other hand, if you want to add restrictions, you should set position and angle directly, instead of using the relative Translate()/Rotate() methods. This way, you have more control over the resulting values. For example:

``````currX=transform.position.x; // get current value
transform.position.x=Mathf.Clamp(currX,minX,maxX)); // make sure it stays within a given interval
``````

You can do something similar for rotation (using transform.eulerAngles), but you need to take care of wraparound effects: if you set transform.localEulerAngles.y=-10, next time you query the value, it will return 350, not -10. You have to take this into account when restricting this to certain angles.
One way to do this, which however only works if you don’t modify the the transform’s rotation anywhere else, is to query the value only at the beginning, and then always refer to that value and never query transform.localEulerAngles.y, only setting it.