Glass pane stops enemy before they break it

Godot Version

4.2

Question

I am making a 2D platformer, and i want the player to be able to kick enemies out of buildings through glass. The player kicks like this:

	for body in $KickArea.get_overlapping_bodies():
		if body.is_in_group("kickable"):
			if $Sprite2D.flip_h == false: body.velocity.x += 5000
			else: body.velocity.x = -5000

and the enemy accepts velocity like this:

func _physics_process(delta):
    velocity.y += 4000 * delta
	velocity.x = lerp(velocity.x, 0.0, 0.4)
	move_and_slide()

Glass is Staticbody2D with an Area2D child that checks if the one who enters it has high enough velocity to break it. Area2D’s collision is bigger than Staticbody2D’s collision.
Here’s Area2D’s code:

var playerin = 0
var entered = "none"

func _on_body_entered(body):
	if body.is_in_group("Human"):
		playerin = 1
		entered = body
	
func _on_body_exited(body):
	if body.is_in_group("Human"):
		playerin = 0
		entered = "none"

func _physics_process(delta):
		if playerin ==1 and entered.is_in_group("Human") and (entered.velocity.x > 400 or entered.velocity.x < -400):
			entered.velocity.x = entered.velocity.x
			get_parent().set_collision_layer_value(1, 0)
			get_parent().get_child(2).queue_free()
			get_parent().queue_free()

This works when the player runs into the glass. However, if the enemy is standing not too far from the glass (but not in Area2D’s collision) and is kicked into it, the StaticBody2D stops the enemy before Area2D checks the velocity. It works, however, if the enemy is far from the glass or is in Area2D’s collision already. How do i fix this?

Here are the collisions (red is the Staticbody2D’s collision):
SCREENSHOTCOL

It’s hard to say for sure without seeing the full project,
but I suspect that the enemy is simply moving too quickly, and moving so far in one physics frame that it hits the static wall before the area can trigger.

Instead of relying on the Area2D to detect the enemy, you could instead rely on move_and_slide()'s collision handling.

When you call move_and_slide(), you could then check the collisions, and if the character hits the glass with enough speed, you can break the glass, and then use the collision info to reset the character’s motion and call move_and_slide() again.

Refer to the example in the docs here: Using CharacterBody2D/3D — Godot Engine (stable) documentation in English

1 Like

This worked, thanks for helping despite me not giving much information!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.