How to make a RigidBody2D Turn Into Another RigidBody2D When collision happen ? ( example: Asteroids Explosion )

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

Hello Community :slight_smile:

i’m working on Asteroids shooting Game, and i have a question
how i can make Asteroids split into small ones when i hit them with Laser (Area2D) !!!

i saw some tutorials but the Asteroids were Kinematic-body 2D and i’m writing the code in different way from them

Asteroids Script

extends RigidBody2D
export var MAX_SPEED= 1000
export var MIN_SPEED = 400
var Aster_type=[‘Grey’,‘Red’]

func _ready():
$AnimatedSprite.animation= Aster_type[randi()% Aster_type.size()]
func _on_VisibilityNotifier2D_screen_exited():

main Script (i use timer to spwan Asteroids )

extends Node
export (PackedScene) var Asteroid

func _ready():

func _on_Aster_timer_timeout():
var Aster= Asteroid.instance()
var direction =$Aster_path/Aster_spwan.rotation+ PI/2
direction += rand_range(-PI/4,PI/4)
Aster.rotation = direction

here is an image from the game # Pic from The Game

Thank You :slight_smile:

:bust_in_silhouette: Reply From: fbrunet99

You have a lot of choices of what you can do, but here is one way in Godot 3.1:

1: Add a signal asteroid_hit to your asteroid object.

signal asteroid_hit

2: Emit a signal when you detect a collision with a shot. Return your location (a Vector2) and your size (I assume you will have about 3 sizes like the arcade game does).


emit signal("asteroid_hit", cur_location, cur_size)
# play animation or sounds here

You will want to call queue_free() on your asteroid after your explode animation and sounds are done.
If you are using Tween to do the animation, you can connect to the tween end signal. Otherwise
you could make it happen in a timer after a second or so:

yield(get_tree().create_timer(3.0), "timeout")

3: In your main script, connect the signal with some code that will spawn some smaller asteroids.

Aster.connect("asteroid_hit", self, "on_asteroid_hit")

4: Also in your main script, implement on_asteroid_hit function that takes the parameters from your emitted signal and makes baby asteroids at that location

# When an asteroid is hit, make two smaller child asteroids at that location
func on_asteroid_hit(location, size):
    var new_aster
    for i in range(0, 1):                                     # this could be a random number if you don't always spawn 2
        var size = get_smaller_size(size)
        if size > MIN_SIZE:
            new_aster = $Asteroid.instance()
            new_aster.position = location
            # set the direction etc
            # add_child(new_aster)