2D Bounce Physics and removing Scenes

Godot Version

v4.2.stable.official [46dc27791]


Hi, I’m relatively new to game Dev, I’m trying to make a small physics-based game around a ball bouncing off pegs and removing them when doing so. At the moment it starts off working ok but then quickly starts ignoring the bounce aspect and just removes the pegs from the Scene once hit. I do have a recording but it won’t let me upload it at the moment. Below is my code for the bounce physics. Any help would be appreciated. TIA

func _physics_process(delta):
	velocity = position - old_position
	collision = move_and_collide(velocity * delta)
	old_position = position
	if collision:
		var collided_object = get_node(collision.get_collider().get_path())
		var reflect = collision.get_remainder().bounce(collision.get_normal())
		Formatted_log_messages.log(Formatted_log_messages.message_type.COLLISION, {"ref": reflect, "vel": velocity, "obj": collided_object.name})
		if collided_object.is_killable:
			get_tree().physics_frame.connect(collided_object.kill_self, CONNECT_DEFERRED)


This is what’s happening when I run

I think old_position should be updated before move_and_collide(). And actually I don’t recommend updating velocity based on old position in this case. You could just update velocity with every bounce.

func _physics_process(delta):
    var collision = move_and_collide(velocity * delta)
    if collision:
        if collision.get_collider().is_killable:
        var reflect = collision.get_remainder().bounce(collision.get_normal())
        velocity = velocity.bounce(collision.get_normal())

Also, the line

var collided_object = get_node(collision.get_collider().get_path())

has some redundancy, as it is essentially the same as

var collided_object = collision.get_collider()


Thanks for the help. I have updated my code to reflect your changes and it’s still not quite doing what is needed. It looks like the ball always has a velocity of 0,0 which doesn’t feel right. Also, I have managed to update the original post with a video of what is happening.

What type of node is the ball? If you’re moving it with move_and_collide(), StaticBody2D should work. If the ball is a RigidBody2D, you shouldn’t move it in the code, because the engine already handles the movement.

I was using a RigidBody2D for the ball switching, and it helped get the effect from the bouncing I was looking for. Just need gravity to keep the ball moving downwards now so it curves rather than straight lines. Thanks for your help.