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

如何修复Godot脚本以实现角色墙跳功能?

修复Godot 2D角色墙跳与墙滑问题

你的脚本存在几个关键问题导致墙跳功能失效,以下是修复后的完整代码及问题说明:

extends CharacterBody2D

@export var speed = 400.0
@export var jump_speed = -1400.0
@export var wall_jump_push = 800  # 增大推力数值,确保效果明显
@export var wall_slide_speed = 150  # 墙滑的下落速度(每秒)

var gravity = 4000  # 调整为更合理的重力值(每秒)
var is_wall_sliding = false
var wall_normal = Vector2.ZERO  # 记录墙面的法线方向

func _physics_process(delta):
    # 移除move_and_collide,CharacterBody2D应统一使用move_and_slide
    var input_direction = Input.get_axis("ui_left", "ui_right")
    
    # 处理地面移动
    if is_on_floor():
        velocity.x = input_direction * speed
    # 处理墙滑时的水平速度(贴墙时保持微小推力)
    elif is_wall_sliding:
        if sign(input_direction) == sign(wall_normal.x):
            velocity.x = input_direction * speed * 0.2
    
    # 统一处理重力(非墙滑状态)
    if not is_wall_sliding:
        velocity.y += gravity * delta
    
    # 执行移动,获取碰撞信息用于墙跳判断
    move_and_slide()
    
    # 更新墙滑状态
    update_wall_slide_state()
    
    # 处理跳跃(包含墙跳)
    handle_jump()

func update_wall_slide_state():
    is_wall_sliding = false
    wall_normal = Vector2.ZERO
    
    # 检测是否贴墙且不在地面
    if is_on_wall() and !is_on_floor():
        # 获取墙面的法线方向(用于判断墙跳的反方向)
        for collision in get_slide_collision_count():
            var col = get_slide_collision(collision)
            if col.normal.y == 0:  # 只处理垂直墙面
                wall_normal = col.normal
                is_wall_sliding = true
                break
    
    # 墙滑时设置下落速度
    if is_wall_sliding:
        velocity.y = min(velocity.y, wall_slide_speed)

func handle_jump():
    # 地面跳跃
    if Input.is_action_just_pressed("jump") and is_on_floor():
        velocity.y = jump_speed
    # 墙跳逻辑
    elif Input.is_action_just_pressed("jump") and is_wall_sliding:
        # 向墙面的反方向推(x轴),同时施加向上的跳跃力
        velocity.x = -wall_normal.x * wall_jump_push
        velocity.y = jump_speed * 0.8  # 墙跳高度略低于地面跳跃,更符合手感
        # 短暂脱离墙面,避免立即再次触发墙滑
        is_wall_sliding = false

关键修改点说明:

  • 移除冲突的移动函数:原脚本同时使用move_and_collide和move_and_slide,这两个函数不能混用,CharacterBody2D应统一使用move_and_slide来处理碰撞和移动。
  • 统一重力处理:将重力累加逻辑移到_physics_process中,避免在jump函数里混乱处理,墙滑状态下关闭普通重力,改用固定的墙滑下落速度。
  • 实现完整墙跳逻辑:原wall_jump函数未被调用且逻辑错误,新增的handle_jump函数区分地面跳跃和墙跳,通过墙面法线方向计算水平推力,同时施加向上的跳跃力。
  • 优化墙滑状态检测:通过get_slide_collision_count获取墙面法线,确保墙跳方向正确,同时在墙滑时限制水平速度,让角色更贴合墙面。
  • 调整数值参数:修改重力、墙跳推力、墙滑速度等数值,让手感更符合2D平台游戏的常规体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:13:33