You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#开发贪吃蛇游戏移动方向限制及方向键控制实现咨询

实现方案

完整修改后代码

private Vector2 _direction = Vector2.right;

private void Update()
{
    // 先暂存目标方向,默认和当前方向一致
    Vector2 targetDirection = _direction;

    // 同时支持WASD和方向键输入
    if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow))
    {
        targetDirection = Vector2.up;
    }
    else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow))
    {
        targetDirection = Vector2.down;
    }
    else if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
    {
        targetDirection = Vector2.right;
    }
    else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
    {
        targetDirection = Vector2.left;
    }

    // 方向限制逻辑:目标方向和当前方向不是反方向才允许修改
    // 相反方向的向量相加结果为零向量,以此作为判断依据
    if (targetDirection + _direction != Vector2.zero)
    {
        _direction = targetDirection;
    }
}

实现说明

  • 方向键支持:在原有WASD的按键检测逻辑中,用||运算符增加对应方向键的KeyCode判断,按下两种按键中的任意一种都会触发对应方向的切换逻辑。
  • 反向转向限制:贪吃蛇的相反移动方向向量相加结果为零向量(比如Vector2.up + Vector2.down = (0,0)),我们在更新方向前做判断,只有目标方向不是当前方向的反方向时,才允许修改当前移动方向。

内容的提问来源于stack exchange,提问作者RandomDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:27:02