首页 > 解决方案 > 试图用箭头键移动 1 个对象,用 wasd 移动另一个对象

问题描述

我正在开发一个 2D 游戏,我想用箭头键移动一个左块,用 A 和 D 移动一个右块,但我只能用 WASD 或箭头键移动,我对 C# 和统一。

我尝试制作 2 个“水平”,方法是在项目设置中制作一个 A 和 D,另一个用左箭头和右箭头键制作,但这似乎不起作用,非常感谢:*)

这是给玩家 1

    public float speed;

    private Rigidbody2D rb;
    private Vector2 moveVelocity;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal1"), 0f);
        moveVelocity = moveInput.normalized * speed;
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }

播放器 2 是相同的代码,只是使用 ("Horizo​​ntal2")

标签: c#unity3d

解决方案


您可以Input.GetKey(KeyCode)用来读取玩家的输入。此外,在检查器中为每个玩家分配 KeyCode。

这是一个可能有帮助的示例代码:

public KeyCode leftKey  = KeyCode.A; // Change to KeyCode.LeftArrow in inspector
public KeyCode rightKey = KeyCode.D;
public float   speed = 1.0f;

private Vector2 _moveVelocity;
private RigidBody2D _rigidBody;

private void Start()
{
    _rigidBody = GetComponent<Rigidbody2D>();
}

private void Update()
{
    Vector2 moveInput = Vector2.zero;
    if(Input.GetKey(leftKey))
    {
        moveInput = Vector2.left;
    }

    if(Input.GetKey(rightKey))
    {
        moveInput = Vector2.right;
    }

    _moveVelocity = moveInput * speed * Time.deltaTime;
    _rigidBody.velocity = _moveVelocity;

}



推荐阅读