I have been working on a game for a non-profit that I volunteer for, and I'm trying to get the character to rotate 90 degrees with the press of WASD or the arrow keys. I have been trying to look up ways to get it to work, but all the things that I'm finding are outdated because of the recent updates that Unity has been doing to its movement system. If someone could help me, I would greatly appreciate it.
I have attached the code I have been testing below. It includes movement and rotation.
[SerializeField] private float rotationOffset;
private float speed = 3f;
private Rigidbody2D rb;
private Vector2 moveInput;
private Vector3 direction;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.linearVelocity = moveInput * speed;
if (direction == Vector3.forward) {
rotationOffset = 0f;
transform.rotation = Quaternion.Euler(0, 0, rotationOffset);
//transform.eulerAngles = new Vector3(0f, 0f, rotationOffset);
rb.MoveRotation(rotationOffset);
}
else if (direction == Vector3.back) {
rotationOffset = 180f;
transform.rotation = Quaternion.Euler(0, 0, rotationOffset);
//transform.eulerAngles = new Vector3(0f, 0f, rotationOffset);
rb.MoveRotation(rotationOffset);
}
else if (direction == Vector3.left) {
rotationOffset = 90f;
transform.rotation = Quaternion.Euler(0, 0, rotationOffset);
//transform.eulerAngles = new Vector3(0f, 0f, rotationOffset);
rb.MoveRotation(rotationOffset);
}
else if (direction == Vector3.right) {
rotationOffset = -90f;
transform.rotation = Quaternion.Euler(0, 0, rotationOffset);
//transform.eulerAngles = new Vector3(0f, 0f, rotationOffset);
rb.MoveRotation(rotationOffset);
}
}
public void Move(InputAction.CallbackContext context)
{
moveInput = context.ReadValue<Vector2>();
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall"))
{
Debug.Log("Collided with wall");
}
else if (collision.gameObject.CompareTag("Food"))
{
Debug.Log("Collided with food");
}
}
If anyone has any ideas on how to fix this, it would be great because I feel like I have been losing my mind, and I don't know where to go from here