Moving area2d needs to stop when hitting wall

Godot Version

4.2.2.

Question

Hello. Im making a zombie simulator. My zombie is an area2d node with a sprite and collisionshape 2d. It is constantly moving in random directions. I want it to stop moving or continue moving in another direction when it hits a wall. No matter what kind of node the wall is (static body, tileset, area2d) the zombie just moves through the wall . Can you help me? Im very new to Godot so be gente :slightly_smiling_face:

This is the code for the moving zombie

extends Area2D
var direction = Vector2()
var distance_travelled = 0
var infected = 0

func _ready():
randomize()
choose_random_direction()

func _process(delta):
infected_check()
if infected == 1:
start_move(delta)

func choose_random_direction():
var items = [Vector2.RIGHT, Vector2.LEFT, Vector2.UP, Vector2.DOWN]
var random_index = randi() % items.size()
direction = items[random_index]

func _on_body_entered(body):
infected = 1
choose_random_direction()
distance_travelled = 0

func _on_area_shape_entered(area_rid, area, area_shape_index, local_shape_index):
infected = 1

func infected_check():
if infected == 0:
$Label.text = “frisk”
elif infected == 1:
$Label.text = “syk”

func start_move(delta):
position += direction * 100 * delta
distance_travelled += direction.length() * 100 * delta

if distance_travelled >= 100:
	choose_random_direction()
	distance_travelled = 0

You’ll need to add a characterbody2D with the same collisionshape2D.
I preferr putting the area2D under characterbody2D
(In the node panel, It should look like this)
CharacterBody2D
-CollisionShape2D
-Area2D
–CollisionShape2D

The CollisionShape2D (by itself) requires more script to simulate collision by itself.
It would be wiser if you just use it with the CharacterBody2D node.
(Also, check out the document CharacterBody2D — Godot Engine (stable) documentation in English)

Area2D only detects overlaps with other Area2D, for instance - could be utilized in your game to detect players in zombies view range.

Thanks! Changing it to a characterBody was the solution!

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