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

如何实现按下左右键时旋转Sprite?附现有代码求指导

实现Sprite左右键旋转的解决方案

你可以通过控制Sprite节点的rotation(弧度)或rotation_degrees(角度)属性来实现旋转,结合你的汽车驾驶代码,以下是两种实用实现方式:

方式一:左右键直接控制旋转(与移动独立)

修改原有函数,添加旋转逻辑:

# car driving
func get_car_input(delta):
    var velocity = Vector2.ZERO
    var speed = 500
    # 旋转速度(弧度/秒,可按需调整)
    var rotation_speed = 2.0

    if Input.is_action_pressed("forward"):
        velocity.y = -1
    if Input.is_action_pressed("backward"):
        velocity.y = 1
    if Input.is_action_pressed("left"):
        # 逆时针旋转
        rotation += rotation_speed * delta
        velocity.x = -1
    if Input.is_action_pressed("right"):
        # 顺时针旋转
        rotation -= rotation_speed * delta
        velocity.x = 1

    move_and_slide(velocity * speed)

方式二:汽车朝向移动方向(贴合真实驾驶逻辑)

让汽车自动朝向当前移动方向旋转,左右键控制移动轨迹:

# car driving
func get_car_input(delta):
    var velocity = Vector2.ZERO
    var speed = 500
    # 旋转平滑度(值越小旋转越平缓)
    var rotation_smoothing = 0.1

    if Input.is_action_pressed("forward"):
        velocity.y = -1
    if Input.is_action_pressed("backward"):
        velocity.y = 1
    if Input.is_action_pressed("left"):
        velocity.x = -1
    if Input.is_action_pressed("right"):
        velocity.x = 1

    # 有移动输入时,平滑过渡到目标朝向
    if velocity != Vector2.ZERO:
        var target_rotation = velocity.angle()
        rotation = lerp(rotation, target_rotation, rotation_smoothing)
    
    move_and_slide(velocity * speed)

关键细节:

  • rotation用弧度计算,若习惯角度可替换为rotation_degrees,同时旋转速度改为角度值(如90表示每秒转90度)。
  • delta是帧间隔时间,用来保证旋转速度不受帧率波动影响,需在_process或_physics_process函数中调用该方法(Godot会自动传入delta参数)。
  • lerp函数用于实现平滑旋转,避免角度跳变的生硬感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:40:38