我试图为我的游戏制作一个测试动作脚本,但我遇到了一个奇怪的错误,我认为我不知道如何修复。当我玩我的游戏时,我可以向上和向左移动,但我不能向下或向右移动。我没有任何与此脚本相关的统一错误或警告,所以我不确定发生了什么。
这是我使用的代码:
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);
}
}
当我去掉“moveDown”和“moveLeft”的底片后,down 和 right 起作用了,它们以它们应该的方式移动,但它们的速度明显快于 up 和 left,这很有趣。
有人知道如何解决这个问题吗?
我认为管理移动的最好方法是使用输入系统组件。使用它要容易得多。