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);
}
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
currX+=horiz; // add movement
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.