Detecting collisions

Godot Version

Godot 4.2.2 stable


So I have been using GDscript for a minute now and was wanting to see if I could detect a collision without a Area2D. I have the idea but not the skills to figure it out. Currently my scene looks like this Ball>Sprite2D>CollisionShape2d, and in the main scene I have a collsion shape that I use for collisions and I want to print(“Left Wall touched”) once it is touched and I have problem trying to do so. Here is my code.

extends CharacterBody2D

@export var ball_speed = 100
@onready var left_wall = $"../WallCollision's/LeftWallCollision"

func _ready():
	position = Vector2(0, 0)
	velocity = Vector2(200, 200).normalized() * ball_speed

func _physics_process(delta):
	var collision = move_and_collide(velocity * delta)
	if collision:
		velocity = velocity.bounce(collision.get_normal())
	if collision == left_wall:
		print("Left Wall Touched")

btw the code below is a concept of what I would imagine but I can’t bring it to live.
if collision == left_wall:
** print(“Left Wall Touched”)**
If it makes no sense that is why, would love to see if this is even possible, Thanks.

I previously did this with rectangles that move with the sprites. You can add all sprites that have the chance of colliding into groups and then run the checks if there is an overlap. And of course you can also do this with other simple shapes.
It’s also up to you if you use something like a color rect or define the rect as a attribute of another class.

My first prototype in Godot of a similar kind did not use move_and_slide though. Consistently updating the position of the sprite image without any physics may be possible for you.

Hope this helps.

1 Like

If you check the documentation for move_and_collide, you’ll learn that it does return a KinematicCollision2D. So in order to get the actual object your player collided with, you’d have to compare collision.collider to your left_wall variable.

1 Like

Thanks so much, I wish luck to you and your game.

Thanks, I have issue reading the documentation though I know it is simple, I am just kinda ignorant right now. I am going to read this and see what I can implement.

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