gpt4 book ai didi

c# - 如何在 Unity 中使用 WASD 移动二维对象

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:40 26 4
gpt4 key购买 nike

我下面的代码只适用于水平移动。垂直运动不应该也起作用吗?我刚刚开始使用基本的 2D Unity 编程:

public class Player : MonoBehaviour {

//These fields will be exposed to Unity so the dev can set the parameters there
[SerializeField] private float speed = 1f;
[SerializeField] private float upY;
[SerializeField] private float downY;
[SerializeField] private float leftX;
[SerializeField] private float rightX;

private Transform _transformY;
private Transform _transformX;
private Vector2 _currentPosY;
private Vector2 _currentPosX;

// Use this for initialization
void Start () {
_transformY = gameObject.GetComponent<Transform> ();
_currentPosY = _transformY.position;

_transformX = gameObject.GetComponent<Transform> ();
_currentPosX = _transformX.position;
}

// Update is called once per frame
void Update () {
_currentPosY = _transformY.position;
_currentPosX = _transformX.position;

float userInputV = Input.GetAxis ("Vertical");
float userInputH = Input.GetAxis ("Horizontal");

if (userInputV < 0)
_currentPosY -= new Vector2 (0, speed);

if (userInputV > 0)
_currentPosY += new Vector2 (0, speed);

if (userInputH < 0)
_currentPosX -= new Vector2 (speed, 0);

if (userInputH > 0)
_currentPosX += new Vector2 (speed, 0);

CheckBoundary ();

_transformY.position = _currentPosY;
_transformX.position = _currentPosX;
}

private void CheckBoundary(){
if (_currentPosY.y < upY)
_currentPosY.y = upY;

if (_currentPosY.y > downY)
_currentPosY.y = downY;

if (_currentPosX.x < leftX)
_currentPosX.x = leftX;

if (_currentPosX.x > rightX)
_currentPosX.x = rightX;
}
}

如果我删除/注释掉 _currentPosX 及其相关代码,那么我的垂直移动就会起作用。但是,如果我删除/注释掉 _currentPosY 及其相关代码,那么我的水平移动就会起作用。

但我为什么无法让它们同时工作?我想我只是遗漏了一些东西,但我无法弄清楚,因为我只是这方面的初学者。

感谢任何能提供建议的人。

编辑:进一步说明...

我正在编写一个简单的 2d 游戏,玩家可以使用 WASD 键在 4 个方向上移动。

W = move up
A = move left
S = move down
D = move right

我的主要问题是我可以让两个键只在一个轴上工作:A 和 D 对水平运动起作用,而 W 和 S 对垂直运动根本不起作用,反之亦然。

最佳答案

您不需要那些 if 语句。只需使用 += 将输入附加到当前转换位置。

在没有刚体的情况下移动:

public float speed = 100;
public Transform obj;

public void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

Vector3 tempVect = new Vector3(h, v, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;

obj.transform.position += tempVect;
}

使用 Rigidbody2D 移动对象:

public float speed = 100;
public Rigidbody2D rb;

public void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

Vector3 tempVect = new Vector3(h, v, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
rb.MovePosition(rb.transform.position + tempVect);
}

如果您希望稍后能够检测碰撞,我建议使用第二个代码并移动刚体。

注意:

您必须将要移动的对象分配到编辑器中的 obj 槽中。如果使用第二个代码,将具有 Rigidbody2D 的对象分配给编辑器中的 rb 插槽。

关于c# - 如何在 Unity 中使用 WASD 移动二维对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com