unity-game-engine2drigid-bodies

Why does my 2D movement in Unity only move up and left but not down and right?


I was trying to make a test movement script for my game, but I encountered a weird error that I don't think I have any idea of how to fix. When I play my game, I can move up and left just fine, but I am unable to move down or right. I do not have any errors or warnings in unity that are related to this script, so I'm not sure what's happening.

Here's the code I used:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TopDownMovementScript : MonoBehaviour
{
public float speed = 10;
Vector3 moveUp = Vector3.zero;
Vector3 moveDown = Vector3.zero;
Vector3 moveLeft = Vector3.zero;
Vector3 moveRight = Vector3.zero;
public float rigidbody2DYPosition = 0;
public float rigidbody2DXPosition = 0;

public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    rigidbody2DYPosition = rb.position.y;
    rigidbody2DXPosition = rb.position.x;
    moveUp = new Vector3(rb.position.x, rigidbody2DYPosition += speed);
    moveDown = new Vector3(rb.position.x, rigidbody2DYPosition += -speed);
    moveLeft = new Vector3(rigidbody2DXPosition += -speed, rb.position.y);
    moveRight = new Vector3(rigidbody2DXPosition += speed, rb.position.y);
    if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
    {
        rb.MovePosition(moveUp);
    }
    if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
    {
        rb.MovePosition(moveDown);
    }
    if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    {
        rb.MovePosition(moveLeft);
    }
    if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    {
        rb.MovePosition(moveRight);
    }
    Debug.Log(moveDown);
    Debug.Log(moveRight);
}

}

When I removed the negatives from "moveDown" and "moveLeft", the down and right worked, and they moved in the way they should, but their speed was noticeably faster than the up and left, which is interesting.

Does anyone know how to fix this?


Solution

  • I think the best way to manage movement would be to use Input system component. It is much easier to work with.