Search code examples
godot

Godot collision detection


area2D and Sprites with collisionShape2D

Im trying to get the following working- it's a player that moves by W via transform and moves to mouse cursor. What I cant get is the colision with a crate.

I made the area2d and attached to it a player sprite2d and a colisionshape2d with a recatangle When i pass through the crate it does nothing

can anyone assist ive literally tried everything so far//

   extends Area2D


# Called when the node enters the scene tree for the first time.
func _ready():
    pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    pass
    

func _on_area_entered(area):
    if area.name == "Player":
        print("PLAYER ENTERED THE CRATE");

Game 2D view click here


Solution

  • Are you editing the transform position manually? If you're manually updating a Sprite2D's position, it's not doing collision checks. You just set the position to whatever you want.

    You could tap into the Area2D's area_entered signal to perform a manual check to see if your movement would cause an intersection, and then undo the movement if it would, but that's not what I would recommend.

    I can't know your specific use case, but if I were in your situation I would want to replace the player with a CharacterBody2D node. You can add your sprite and collider to this node, and you can use the CharacterBody's move_and_slide function to move your character, instead of editing the transform yourself. This is, for most use cases, the intended solution for a player-controlled 2D object in Godot.

    Hope this helped!