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
相关产品推荐
相关产品推荐

