在move_and_slide 之前和之后跟踪is_on_floor 的更简单方法。
例如:
var was_on_floor = is_on_floor()
move_and_slide(velocity, Vector2.UP)
if is_on_floor() and not was_on_floor:
$sound.play()
每当您调用move_and_slide 时,Godot 都会更新您从is_on_floor、is_on_wall 和is_on_ceiling 获得的值。要知道什么是墙壁、地板或天花板,Godot 使用您传递的向量作为第二个参数(如果您传递Vector2.ZERO,那么一切都是墙壁)。
如果您只想检查它是否与某物发生碰撞,您可以在move_and_slide 之后使用get_slide_count。如果没有冲突,函数get_slide_count 应该给你0:
if get_slide_count() > 0:
$sound.play()
或者您可以检查move_and_slide 返回的速度是否与您通过的速度不同。意味着它确实发生了碰撞(或滑动)。
var old_velocity = velocity
velocity = move_and_slide(velocity, Vector2.UP)
if velocity != old_velocity:
$sound.play()
您也可以使用get_slide_collision,它会为您提供KinematicCollision2D 对象:
for i in get_slide_count():
var collision = get_slide_collision(i)
print("Collided with: ", collision.collider.name)
这会让你识别KinematicBody2D与什么碰撞,然后你可以相应地选择一个声音。