Hello, I’m currently trying to make my player character move around the map, but for some reason, it will not move left and right (it will play the animation trigger however) and it can only move up and down in a restricted space. Currently my code for movement looks like this:
public class PlayerMovement : MonoBehaviour {
[SerializeField]
private float speed;
[SerializeField]
private Animator animator;
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 currentVelocity = gameObject.GetComponent<Rigidbody2D>().velocity;
float newVelocityX = 0f;
if (moveHorizontal < 0 && currentVelocity.x <= 0)
{
newVelocityX = -speed;
animator.SetInteger("DirectionX", -1);
}
else if (moveHorizontal > 0 && currentVelocity.x >= 0)
{
newVelocityX = speed;
animator.SetInteger("DirectionX", 1);
}
else
{
animator.SetInteger("DirectionX", 0);
}
float newVelocityY = 0f;
if (moveVertical < 0 && currentVelocity.y <= 0)
{
newVelocityY = -speed;
animator.SetInteger("DirectionY", -1);
}
else if (moveVertical > 0 && currentVelocity.y >= 0)
{
newVelocityY = speed;
animator.SetInteger("DirectionY", 1);
}
else
{
animator.SetInteger("DirectionY", 0);
}
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(newVelocityX, newVelocityY);
}
I’m not entirely sure where I went wrong, and why my character isn’t moving left and right. I’m wondering if it has something to do with my map, since all objects are on one layer, meaning the ground and collidable objects such as trees have sort of overlapped, but I don’t know how to separate them into different layers.
If anyone knows how to help, I’d really appreciate it.