Hello,
I’m trying to make a basic 2D top down player controller, but I’m having an issue with my Rotate() method, it’s supposed to make the player rotate to look at the mouse.
Rotate() works fine when player is idle, but when I start moving while moving around my cursor Rotate() becomes inaccurate.
7pydb
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Vector3 _mousePosition;
private Vector2 _movement;
private Rigidbody2D _rb2D;
private Camera _camera;
[Header("Speed")]
public float walkSpeed = 5.0f;
private void Start()
{
_camera = Camera.main;
_rb2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
HandleInput();
if (Time.frameCount % 2 == 0) Rotate();
}
private void FixedUpdate()
{
Move(_movement);
}
private void Rotate()
{
var dir = Input.mousePosition - _camera.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
_rb2D.MoveRotation(Quaternion.AngleAxis(angle, Vector3.forward));
}
private void HandleInput()
{
_movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
private void Move(Vector2 direction)
{
direction = direction.normalized;
_rb2D.MovePosition((Vector2) transform.position + walkSpeed * Time.fixedDeltaTime * direction);
}
}
Thanks for reading