Collision does not work

Godot Version

Godot Engine v4.2.1.stable.official

Question

I have a problem that I can’t solve, after watching several videos on how to set up the tilemap system and these collisions, my character doesn’t experience them. In my opinion, this is due to the code for moving the character, but as I’m just starting out, I lack experience and can’t solve my problem.

extends Area2D
@export var speed = 200
var screen_size
# Called when the node enters the scene tree for the first time.
func _ready():
	screen_size = get_viewport_rect().size


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	var velocity = Vector2.ZERO
	if Input.is_action_pressed("Up"):
		velocity.y -= 1
	if Input.is_action_pressed("Down"):
		velocity.y += 1
	if Input.is_action_pressed("Right"):
		velocity.x += 1
	if Input.is_action_pressed("Left"):
		velocity.x -= 1
		
	if velocity.length() > 0:
		velocity = velocity.normalized() * speed;
		$AnimatedSprite2D.play("Run")
	else:
		$AnimatedSprite2D.play("Idle")
		
	position += velocity * delta;
	position = position.clamp(Vector2.ZERO, screen_size)
	if velocity.x !=0 :
		$AnimatedSprite2D.flip_h= velocity.x < 0
	
		

If you want your player or any object interact with the physics system, you need to use a CharacterBody2D or a RigidBody2D. Area2D can be use to detect collision but don’t care about physics.

I’ve already tried it, but it doesn’t work either.

So, first thing to do is switch the player’s root node type to CharacterBody2D. Areas will only report collisions, but won’t stop movement when a collision is detected.

The second thing to do is to stop updating position directly. Instead, use either the move_and_slide or move_and_collide methods built in to CharacterBody2D. You can read the CharacterBody2D docs if you need help picking which one to use. When in doubt, use move_and_slide.

Finally, if that’s not working for you, make sure to check the collision layers for both the CharacterBody2D and the Tile Map. You’ll want to make sure that the player is set up to detect collisions on the same layer you painted the tiles with. You can view these settings in the inspector when clicking on the player’s root node.

For example, here’s a player set up to detect collisions on layer 2:
physics-layers

And here’s the physics setup on the Tile Set resource. It’s set up to report itself in Layer 2:
physics-layers-tile-set-resource

1 Like

Thank you, that solved my problem, but now my character shakes when he moves forward why?