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

Godot调用move_and_slide()报错:参数过多,预期最多0个却收到1个

解决CharacterBody2D调用move_and_slide()报错的问题

你的代码报错核心是Godot版本API差异:你用的是Godot 4,但写法沿用了Godot 3的move_and_slide()调用逻辑,两者的实现规则不一样:

  • Godot 3中move_and_slide()接受速度向量作为参数
  • Godot 4中该方法不再接收任何参数,必须先给节点的velocity属性赋值,再调用无参的move_and_slide()

修正后的完整代码:

extends CharacterBody2D

# Movement speed
var speed = 100 
var player_position
var target_position
# Get a reference to the player. 
@onready var player = get_parent().get_node("Player")
 
func _physics_process(delta):
    # Set player_position to the position of the player node
    player_position = player.position
    # Calculate the direction to player
    target_position = (player_position - position).normalized()
 
    if position.distance_to(player_position) > 1:
        velocity = target_position * speed
        move_and_slide()
        look_at(player_position)

补充两点注意事项:

  • target_position是归一化后的方向向量,乘以speed得到的是每秒移动的速度值,直接赋值给velocity即可
  • move_and_slide()会自动处理物理帧的时间补偿和碰撞响应,无需手动将速度乘以delta

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:03:15