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

Unity无尽跑酷游戏:飞船按键绕Z轴旋转松开复位实现求助

解决Unity飞船左右旋转复位问题

要实现你需要的「按A/D/左右箭头时飞船绕Z轴轻微旋转,松开后复位」的效果,直接在现有代码基础上添加旋转控制变量和逻辑即可,具体修改如下:


1. 添加旋转控制变量

在脚本顶部新增两个公开变量,用来调整旋转的平滑速度和最大角度(数值可根据手感调整):

public float rotateSpeed = 10f; // 旋转过渡的平滑速度
public float maxRotateAngle = 15f; // 左右旋转的最大角度

2. 补充旋转逻辑

在canMove的判断块内添加旋转处理代码,通过平滑过渡实现旋转和自动复位:

修改后的完整脚本代码:

public float moveSpeed = 6;
public float leftRightSpeed = 5;
public float topBottomSpeed = 5;
public float rotateSpeed = 10f; // 旋转平滑速度
public float maxRotateAngle = 15f; // 最大旋转角度
static public bool canMove = false;

void Update()
{
    transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed, Space.World);
    
    if(canMove)
    {
        // 左右移动逻辑
        if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            if(transform.position.x > LevelBoundary.leftSide)
            {
                transform.Translate(Vector3.left * Time.deltaTime * leftRightSpeed);
            }
        }
        if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            if(transform.position.x < LevelBoundary.rightSide)
            {
                transform.Translate(Vector3.right * Time.deltaTime * leftRightSpeed);
            }
        }

        // 上下移动逻辑
        if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            if(transform.position.y < LevelBoundary.topSide)
            {   
                transform.Translate(Vector3.up * Time.deltaTime * topBottomSpeed);
            }
        }
        if(Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            if(transform.position.y > LevelBoundary.bottomSide)
            {
                transform.Translate(Vector3.down * Time.deltaTime * topBottomSpeed);
            }
        }

        // 旋转复位逻辑
        float targetRotationZ = 0f;
        // 按左方向键时,飞船绕Z轴顺时针旋转(负角度)
        if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            targetRotationZ = -maxRotateAngle;
        }
        // 按右方向键时,飞船绕Z轴逆时针旋转(正角度)
        else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            targetRotationZ = maxRotateAngle;
        }

        // 平滑过渡到目标旋转角度,松开按键后自动复位到0
        Quaternion targetRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, targetRotationZ);
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
    }
}

逻辑说明

  • 用Quaternion.Lerp实现平滑旋转,避免生硬的角度跳转,提升操作手感
  • 通过targetRotationZ动态设置目标角度:按键时设为对应旋转角度,松开后自动回归0度
  • 可在Unity Inspector面板中调整rotateSpeed和maxRotateAngle的值,匹配游戏的操作节奏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:23:38