how to get directional collision detection area2d

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

Using Area2D nodes, I want an event that is called only when it collides with something to the right or left of it, and not to the top or bottom. I’m making a basic enemy ai which i want it so that when it collides with the right or left changes direction

Here’s the code:

extends Area2D

signal damage_player

var motion = Vector2()
var is_going_backwards = false

func _on_Area2D_body_entered(body):
var bodies = get_overlapping_bodies()

for body in bodies:
	if body.name == "Player":
		emit_signal("damage_player")

if is_going_backwards == true:
	is_going_backwards = false
else:
	is_going_backwards = true

func _physics_process(delta):
if is_going_backwards == true:
motion.x = -1
$AnimatedSprite.flip_h = true
else:
motion.x = 1
$AnimatedSprite.flip_h = false
move_local_x(motion.x)

1 Like
:bust_in_silhouette: Reply From: Magso

Check which side the colliding body is on in body_entered.

if body.global_position.x < global_position.x:
    #body collided on the left side.

global_position is a property, not a method, so remove the ().

kidscancode | 2019-04-04 20:01

wouldn’t that still detect collision below or above the body?

idk tbh | 2019-04-05 09:44

It would yes, if the area has a width then you can see if body X global position is within the width of the area’s X scale by taking the X global position of the area and + or - half of the width. This collision would have collided from the top or bottom.

Magso | 2019-04-05 11:17

Sorry for the stupid question, I’m new to godot, but how would I go about adding a height and width to the area2d?

idk tbh | 2019-04-05 12:35

Make a CollisionShape2D child, select a shape in the inspector and click and drag to size. All collision shapes will work like this as long as the parent is an area or a body of some kind. Also don’t mix up 2D with 3D.

Magso | 2019-04-05 15:55

ah, i did that already with a collision polygon2d. Thanks for clarifying that that was how its done

idk tbh | 2019-04-05 17:09

1 Like