Collisions
Collisions are a key feature of almost every game, allowing characters to walk on platforms, collect coins,
or take damage from enemies. TCJSgame v3 includes simple collision detection through the
crashWith()
method. This checks if the current component is overlapping with another component
and returns true
or false
.
Collisions are based on rectangular bounding boxes. This means if two rectangles overlap on the canvas, the method will detect a crash. While this isn’t pixel-perfect, it works for most 2D games and is fast enough for many objects at once.
Syntax
if (component.crashWith(otherComponent)) {
// handle collision
}
Example
const player = new Component(30, 30, "blue", 50, 50, "rect");
const wall = new Component(100, 20, "black", 200, 300, "rect");
display.add(player);
display.add(wall);
function update() {
player.x += 1;
if (player.crashWith(wall)) {
console.log("Collision detected!");
player.x -= 1; // stop moving
}
}
Notes
- Only rectangular collisions are supported by default.
- You can combine gravity + collisions for platformer physics.
- Check collisions inside
update()
for real-time results.