'm making this 3D top-down project, and I need the character to turn with the WASD keys (turn only in those directions, no diagonals), at the moment, the vertical part seems to be turning smoothly, but once I press ‘A’ or ‘D’ the player stops turning correctly(even with the ‘W’ or ‘S’ keys).
Here’s my code so far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 5f;
public float gravity = -19f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public Inventory inventory;
public int _rotationSpeed = 180;
public GameObject Hand; // to put objects directly on the hand of the player
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
HandleShootInput();
GetKeyPressed();
}
private void GetKeyPressed()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
if (this.transform.rotation.eulerAngles.y == 0 || this.transform.rotation.eulerAngles.y == 90 || this.transform.rotation.eulerAngles.y == 180 || this.transform.rotation.eulerAngles.y == 270)
{
if (Input.GetKey(KeyCode.W))
{
if (this.transform.rotation.eulerAngles.y == 90)
{
//if in 90º dont rotate
}
else //else rotate to desired rotation
{
Vector3 rotation = new Vector3(0, 90, 0);
this.transform.Rotate(rotation);
}
Vector3 move = transform.forward * z; // the direction we want to move to
controller.Move(move * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
if (this.transform.rotation.eulerAngles.y == 270)
{
//if in 90º dont rotate
}
else //else rotate to desired rotation
{
Vector3 rotation = new Vector3(0, 270, 0);
this.transform.Rotate(rotation);
}
Vector3 move = transform.forward * (-z); // the direction we want to move to
controller.Move(move * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
if (this.transform.rotation.eulerAngles.x == 180)
{
//if in 90º dont rotate
}
else //else rotate to desired rotation
{
Vector3 rotation = new Vector3(0, 180, 0);
this.transform.Rotate(rotation);
}
Vector3 move = transform.forward * z; // the direction we want to move to
controller.Move(move * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
if (this.transform.rotation.eulerAngles.y == 0)
{
//if in 90º dont rotate
}
else //else rotate to desired rotation
{
Vector3 rotation = new Vector3(0, 0, 0);
this.transform.Rotate(rotation);
}
Vector3 move = transform.forward * -z; // the direction we want to move to
controller.Move(move * speed * Time.deltaTime);
}
}
else
{
}
}
}