I want to keep using the Rigidbody 2d on the player but when i move the player while he is moving, he also make rotations like losing control.
in the Rigidbody of the transform i set the Gravity Scale to 0.
The goal is when i move the player up he will move up straight directly but then when getting to the corner when i will click the right key for example he will rotate and turn facing right.
I tried to add in the Start a freeze rotation:
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.freezeRotation = true;
}
but this is not a solution. because the freeze rotation makes the player sometimes stuck at the walls and not continue moving my guess because the sprite try to rotate or something with the rigidbody and the freeze rotation make it stuck.
screenshot:
the player is in red. first the player should be always in the middle center of the path and never each to the end touch the wall/s and how to fix the rotation issue too.
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
public float speed = 5f;
private Rigidbody2D rb;
private Vector2 movement;
private bool isMoving = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Get input from player and only allow cardinal direction movement
if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W))
{
movement = Vector2.up;
isMoving = true;
}
else if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S))
{
movement = Vector2.down;
isMoving = true;
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
{
movement = Vector2.left;
isMoving = true;
}
else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
{
movement = Vector2.right;
isMoving = true;
}
}
void FixedUpdate()
{
if (isMoving)
{
// Move player smoothly
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Circle"))
{
Destroy(collision.gameObject);
}
}
}