尝试使用箭头键移动一个对象,并使用wasd

时间:2019-05-11 20:35:58

标签: c# unity3d

我正在开发2D游戏,我想使用方向键向左移动一个块,使用A和D来向右移动一个块,但是我只能使用WASD或方向键进行一个移动,我很新到C#和Unity。

我尝试通过在Project Settings中创建一个A和D以及另一个使用左箭头和右箭头键来制作2个“水平”,但这似乎不起作用,非常感谢:*)< / p>

这是给玩家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”)

1 个答案:

答案 0 :(得分:0)

您可以使用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;

}


相关问题