Godot 4.2.1中move_and_slide调用报错求助
解决Godot 4.2.1中
move_and_slide()的报错问题 错误原因
Godot 4对CharacterBody3D的move_and_slide() API做了核心调整:
- 该函数不再需要传入任何参数(velocity、上方向、滑动参数等),相关配置改为通过节点属性设置;
- 函数返回值为
bool类型(表示角色是否产生有效移动),无法赋值给Vector3类型的velocity变量,这是类型不匹配错误的直接原因。
修复步骤
只需修改调用move_and_slide()的代码行:
原错误代码:
velocity = move_and_slide(velocity, Vector3.UP, true, 4, deg_to_rad(45))
修改为:
move_and_slide()
保留原参数功能的配置(可选)
如果需要还原你原本传入参数的效果,可通过设置CharacterBody3D的属性实现:
- 原参数
Vector3.UP:对应节点的up_direction属性,默认值即为Vector3.UP,无需修改; - 原参数
true(停止在斜坡上):在代码中添加stop_on_slope = true,或在编辑器属性面板勾选Stop On Slope; - 原参数
4(最大滑动次数):对应节点的max_slides属性,默认值即为4; - 原参数
deg_to_rad(45)(最大地面角度):对应节点的floor_max_angle属性,默认值即为deg_to_rad(45),无需修改。
完整修复后的代码
extends CharacterBody3D const MOUSE_SENSITIVITY = 0.1 @onready var camera = $CamRoot/Camera # Movement var current_vel = Vector3.ZERO var dir = Vector3.ZERO const SPEED = 10 const SPRINT_SPEED = 20 const ACCEL = 15.0 # Jump const GRAVITY = -40.0 const JUMP_SPEED = 15 var jump_counter = 0 const AIR_ACCEL = 9.0 func _ready(): Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) # 可选:启用斜坡停止功能 stop_on_slope = true func _process(delta): window_activity() func _physics_process(delta): # Get the input directions dir = Vector3.ZERO if Input.is_action_pressed("forward"): dir -= camera.global_transform.basis.z if Input.is_action_pressed("backward"): dir += camera.global_transform.basis.z if Input.is_action_pressed("right"): dir += camera.global_transform.basis.x if Input.is_action_pressed("left"): dir -= camera.global_transform.basis.x # Normalizing the input directions dir = dir.normalized() # Apply gravity velocity.y += GRAVITY * delta if is_on_floor(): jump_counter = 0 # Jump if Input.is_action_just_pressed("jump") and jump_counter < 2: jump_counter += 1 velocity.y = JUMP_SPEED # Set speed and target velocity var speed = SPRINT_SPEED if Input.is_action_pressed("sprint") else SPEED var target_vel = dir * speed # Smooth out the player's movement var accel = ACCEL if is_on_floor() else AIR_ACCEL current_vel = current_vel.linear_interpolate(target_vel, accel * delta) velocity.x = current_vel.x velocity.z = current_vel.z # 修复后的move_and_slide调用 move_and_slide() func _input(event): if event is InputEventMouseMotion: # Rotates the view vertically $CamRoot.rotate_x(deg_to_rad(event.relative.y * MOUSE_SENSITIVITY * -1)) $CamRoot.rotation_degrees.x = clamp($CamRoot.rotation_degrees.x, -75, 75) # Rotates the view horizontally self.rotate_y(deg_to_rad(event.relative.x * MOUSE_SENSITIVITY * -1)) # To show/hide the cursor func window_activity(): if Input.is_action_just_pressed("ui_cancel"): if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) else: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
内容的提问来源于stack exchange,提问作者Luciano Arancibia
相关产品推荐
相关产品推荐

