Learn how to detect collisions between game objects
Collision detection is essential for creating interactive games. Talon provides Raylib’s comprehensive collision detection functions for rectangles, circles, points, and more.
The asteroid game demonstrates collision detection between the player ship and meteors:
1
Set up player collider
class Player { construct new(position, speed, acceleration, rotation, collider, color) { _position = position _speed = speed _acceleration = acceleration _rotation = rotation _collider = collider // Vector3 (x, y, radius) _color = color } collider { _collider } collider=(value) { _collider = value }}
2
Update collider position
// Update player collider position based on ship rotationvar DEG2RAD = 0.017453_player.collider = Vector3.new( player.position.x + Math.sin(player.rotation * DEG2RAD) * (_shipHeight / 2.5), player.position.y - Math.cos(player.rotation * DEG2RAD) * (_shipHeight / 2.5), 12 // radius)
3
Check collisions with meteors
// Check collision with medium meteorsfor (i in 0...MAX_MEDIUM_METEORS) { if (Raylib.checkCollisionCircles( Vector2.new(player.collider.x, player.collider.y), player.collider.z, // radius stored in z _mediumMeteor[i].position, _mediumMeteor[i].radius ) && _mediumMeteor[i].active) { _gameOver = true }}// Check collision with small meteorsfor (a in 0...MAX_SMALL_METEORS) { if (Raylib.checkCollisionCircles( Vector2.new(player.collider.x, player.collider.y), player.collider.z, _smallMeteor[a].position, _smallMeteor[a].radius ) && _smallMeteor[a].active) { _gameOver = true }}
The asteroid game uses Vector3 to store circle collision data (x, y, radius) in a single object.
The Breakout game implements intelligent collision response:
class Ball { apply_collission(rec) { var prev_x = _rec.x - _vel.x var prev_y = _rec.y - _vel.y // Determine which side was hit if (prev_y + _rec.height <= rec.y) { // Hit from top _vel.y = _vel.y * -1.0 } else if (prev_y >= rec.y + rec.height) { // Hit from bottom _vel.y = _vel.y * -1.0 } else if (prev_x + _rec.width <= rec.x) { // Hit from left _vel.x = _vel.x * -1.0 } else if (prev_x >= rec.x + rec.width) { // Hit from right _vel.x = _vel.x * -1.0 } else { // Default to vertical bounce _vel.y = _vel.y * -1.0 } }}
Store the previous position to determine which side of an object was hit, enabling accurate collision response.
// Point vs TriangleRaylib.checkCollisionPointTriangle(point, p1, p2, p3)// Point vs LineRaylib.checkCollisionPointLine(point, p1, p2, threshold)// Circle vs LineRaylib.checkCollisionCircleLine(center, radius, p1, p2)// Line vs LineRaylib.checkCollisionLines(startPos1, endPos1, startPos2, endPos2, collisionPoint)// Get collision rectangle (intersection)var intersection = Raylib.getCollisionRec(rec1, rec2)