|
|
|
|
Reply From: |
DodoIta |
If you want to write the code for the collision in the main scene’s script, you should use the connect function, like this:
# get a reference to the player's bullet
var bullet = $Player/Bullet # or whatever the bullet path is
bullet.connect("body_enter", self, "hit_enemy")
func hit_enemy():
# do whatever you need to do
Basically when the bullet’s Area2D emits the “body enter” signal, it executes the “hit_enemy” function, and that’s what connect does.
Thanks for your reply. That’s not quite what I meant. I’m aware of the above code but it makes more logical sense to me to have the Main scene act as a placeholder for all the instances and have all the behaviours coded into the individual scenes themselves. So, I was aiming to have the projectile collision coded into the Projectile scene and then have the Enemy reaction coded into the Enemy scene.
Does that explain it better?
Icarus | 2017-12-10 15:04
Then you could add the enemies to a group, say “Enemies”. Then, in the Projectile’s scene, you connect body_enter
to a function that does:
if body.get_groups().has("Enemies"):
# trigger the enemy's reaction
# trigger the projectile's reaction
DodoIta | 2017-12-10 15:17
This is what I’m looking for! Thanks very much.
Icarus | 2017-12-10 15:19
You’re welcome
DodoIta | 2017-12-10 15:21
Okay, I’ve added the following code:
func _on_Projectile_body_entered(body):
if body.get_groups.has("Enemies"):
print("worked")
It’s connected and I’ve added my Enemy scene to a group called “Enemies”.
It doesn’t print anything. Amy I missing something else?
Icarus | 2017-12-10 15:53
Try printing the body first to see if it’s been passed as an argument, use
print(body.get_name())
and see what happens.
DodoIta | 2017-12-10 15:57
Nothing is printed. The projectile is an Area2D. The enemy is a RigidBody2D. Don’t know if this helps troubleshoot.
Icarus | 2017-12-10 16:27
Then maybe your bullet is too fast and/or the enemy is too small, since the body enter doesn’t seem to be reported. This video explains it well.
You can try using a Raycast or using another Area2D for the enemy (if possible). If you still need the enemy to detect collisions, try instancing an Area2D as a child of the rigidbody
DodoIta | 2017-12-10 17:12
The enemy has a CollisionShape2D so maybe I’ll try swapping that for an Area2D. The bullet is quite slow so I’m sure it should detect. It’s most likely a syntax or hierarchy error on my part.
Icarus | 2017-12-10 17:27