Home > OS >  How do I Rotate 2D Player Using Buttons in Unity
How do I Rotate 2D Player Using Buttons in Unity

Time:01-07

So I'm trying to create a birds-eye shooter game in Unity2D but I can't get my player to rotate with the A&D keys. Anyone have any ideas?

I tried adding my custom variable (float rotateSpeed = 5f;) to my players rotation but it says (Operator ' =' cannot be applied to operands of type 'Quaternion' and 'float') I don't know what else to try

CodePudding user response:

Instead of using Quaternions to rotate your 2D sprite, try using Transform.rotate like so:

void TurnLeft() {
    transform.Rotate(0,0,rotateSpeed);
}

void TurnRight() {
    transform.Rotate(0,0,-rotateSpeed);
}

Now whenever you trigger either function, it will rotate your sprite by that amount in either direction. A positive speed rotates your sprite left, and a negative speed rotates right.

CodePudding user response:

Easiest way is to add an horizontalInput variable and to multiply itself to your rotationSpeed like this :

private float horizontalInput;
[SerializeField] private float speed = 5.0f;

void Update()
{
    horizontalInput = Input.GetAxis("Horizontal");
    // Rotate(x,y,z)
    transform.Rotate(0, horizontalInput * speed * Time.deltaTime, 0);
}

  • Related