How to detect collisions using RigidBody2D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pekweieie

Hey, relatively new to Godot here. I tried coding a bullet (RigidBody2D Node) that would hide itself after hitting a wall. I used the body_entered() signal for when the bullet hits a wall and doesn’t seem to work. idk what I supposed to do here. Also I coded a timer so that the bullet would delete itself after 1 second.

extends RigidBody2D 

var projectile_speed = 1000.0
var lifetime = 1 

func _ready() -> void:
	apply_impulse(Vector2(), Vector2(projectile_speed, 0).rotated(rotation))
	self.contact_monitor = true
	selfdestruct()
	
func _on_Bullet_body_entered(body):
	self.hide()
	
func selfdestruct():
	yield(get_tree().create_timer(lifetime),"timeout")
	queue_free()

Have you checked if the signal is connected?

sinistro25 | 2020-09-12 01:09

:bust_in_silhouette: Reply From: Chafmere

I believe what you need to do is add a Area2d node to your bullet and use that to detect the collision and emit a signal to tell your bullet object to do something.

:bust_in_silhouette: Reply From: sinistro25

I usually implement bullets using a KinematicBody2D because I can set the speed directly with having to use forces. They are moved with functions move_and_collide, this function returns null if there was no collision during the movement, so if the value returned is not null there was a collision.

var collision = move_and_collide(velocity*delta)
  if collision:
    self.hide()
:bust_in_silhouette: Reply From: SteveSmith