Godot 2D平滑玩家移动脚本报错求助
俯视角2D玩家移动脚本错误修复
错误原因与修复方案
1. velocity 重定义错误(Line 9)
CharacterBody2D类本身自带velocity成员变量,你自定义的var velocity = Vector2.ZERO与原生属性冲突,导致报错。
- 修复:删除自定义的
velocity变量,直接使用CharacterBody2D自带的velocity属性即可。
2. linear_velocity 未定义错误(Line 48)
linear_velocity是Godot 3中KinematicBody2D的属性,Godot 4里的CharacterBody2D改用velocity控制移动,且需要调用move_and_slide()才能完成实际移动。
- 修复:删除
linear_velocity = velocity,替换为move_and_slide()。
修改后的完整代码
const SPEED = 200 const FRICTION = 5 const DASH_SPEED = 400 const DASH_DURATION = 0.1 const DASH_COOLDOWN = 1.5 var dashTimer = 0 var canDash = true func _physics_process(delta: float) -> void: # Player movement var inputVector = Vector2.ZERO if Input.is_action_pressed("ui_up"): inputVector.y -= 1 if Input.is_action_pressed("ui_down"): inputVector.y += 1 if Input.is_action_pressed("ui_left"): inputVector.x -= 1 if Input.is_action_pressed("ui_right"): inputVector.x += 1 # Apply friction if inputVector == Vector2.ZERO: velocity = velocity.linear_interpolate(Vector2.ZERO, FRICTION * delta) else: velocity += inputVector.normalized() * SPEED * delta # Perform dash if canDash and Input.is_action_just_pressed("dash"): var dashDirection = get_global_mouse_position() - position var dashDistance = dashDirection.length() if dashDistance > 0: dashDirection = dashDirection.normalized() velocity = dashDirection * DASH_SPEED dashTimer = DASH_DURATION canDash = false # Apply dash cooldown if not canDash: dashTimer -= delta if dashTimer <= 0: canDash = true # 执行移动(CharacterBody2D必需调用此方法) move_and_slide()
内容的提问来源于stack exchange,提问作者TriggerFox Games
相关产品推荐
相关产品推荐

