Reputation: 51
The player in my game is a kinematicbody2D, and I want a sound effect to play whenever it collides with the tile map. My player uses move_and_slide()
to collide with the tile map.
How can I trigger a sound to play when the player hits the tilemap? I only want the sound to play after the player initially collides with the tile map; it shouldn’t play over and over if the player is sitting on the floor.
I know how to use sounds with the StreamAudioPlayer, I just need help triggering the sound to play when I want it to play.
Upvotes: 2
Views: 1115
Reputation: 40220
The simpler way to keep track of is_on_floor
before and after move_and_slide
.
For example:
var was_on_floor = is_on_floor()
move_and_slide(velocity, Vector2.UP)
if is_on_floor() and not was_on_floor:
$sound.play()
Whenever you call move_and_slide
Godot updates the values you get from is_on_floor
, is_on_wall
and is_on_ceiling
. To know what is wall, floor or ceiling, Godot uses the vector you pass as second parameter (if you pass Vector2.ZERO
then everything is wall).
If you only care to check if it collided with something at all, you may use get_slide_count
after move_and_slide
. The function get_slide_count
should give you 0
if there were no collisions:
if get_slide_count() > 0:
$sound.play()
Or you could check if the velocity that move_and_slide
returns a different velocity that the one you passed. Meaning it did collide (or slide).
var old_velocity = velocity
velocity = move_and_slide(velocity, Vector2.UP)
if velocity != old_velocity:
$sound.play()
Alternatively you may use get_slide_collision
, which gives you a KinematicCollision2D
object:
for i in get_slide_count():
var collision = get_slide_collision(i)
print("Collided with: ", collision.collider.name)
Which will let you identify with what did the KinematicBody2D
collide with, and then you could pick a sound accordingly.
Upvotes: 1