Home > Software engineering >  How can I make a Player object rotate using the A and D keys in Unity 3D?
How can I make a Player object rotate using the A and D keys in Unity 3D?

Time:01-25

I need some help as someone brand new to Unity and C# coding. The problem that I am currently facing is that I need my player model to only be able to rotate left and right instead of move on all three axis like many tutorials I have found online. The code I have currently got is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerRotation : MonoBehaviour
{
    private void Update()
    {
        Rigidbody rb = GetComponent<Rigidbody>();
        if (Input.GetKey(KeyCode.A))
        rb.AddForce(Vector3.left);
        if (Input.GetKey(KeyCode.D))
        rb.AddForce(Vector3.right);
    }

}

But the issue with this is that instead of rotating, the player physically moves left and right. Is anyone able to help with this? (preferably with some code)

CodePudding user response:

Instead of rigidboy, you can directly use the object's transform. So you won't have any problems.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerRotation : MonoBehaviour
{
    public float turnSpeed;
    private void Update()
    {
        if (Input.GetKey(KeyCode.A))
           transform.Rotate(Vector3.left * turnSpeed);
        if (Input.GetKey(KeyCode.D))
           transform.Rotate(Vector3.right * turnSpeed);
    }
}
  •  Tags:  
  • Related