Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 5, 2022 09:43 pm GMT

Collision detection in 2D game development with JavaScript

Collision detection also known as hit testing is simply determining when two objects come in contact with one another.

The collision of objects underlies most game experiences and user-interfaces.
Baseball bats collide with balls, zombies bump into walls, and Mario lands on platforms and stomps turtles.

Mario lands on platforms and stomps turtles

A General Formula For Collision Detection

Detect the positions of each object, compare and calculate if they're overlapping.

Instances

Examples of collision between two objects:-

  1. POINT/POINT
  2. CIRCLE/CIRCLE
  3. RECTANGLE/RECTANGLE

  4. Point/Point
    The easiest collision to test is between two points, to test if they're colliding, we simply check if their X and Y co-ordinates are the same! (i.e if their positions are same).

if (x1 == x2 && y1 == y2) {  // Points are in the same place: collision}else {// Not colliding}
  1. Circle / Circle

Imagine you have two circles, each with their own radius. They are placed with a distance between them. The circles would overlap if the distance is smaller than the sum of the radius of both circles.

Calculating the distance between 2 circles

Calculating the distance between the center of the two circles requires us to remember middle school math and the Pythagorean Theorem:
Opp + Adj = Hyp simply x + y = d;
d = (x + y);

Translated to code, it looks like this:

d = Math.sqrt((x*x) + (y*y))

So, if this distance is smaller than or equal to the radius of circle-a plus radius of circle-b, the circles overlap or touch. This principle is used in the next function:

const circlesCollide = (x1, y1, r1, x2, y2, r2) => {    // Calculate the distance between the two circles    let squareDistance = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);    // When the distance is smaller or equal to the sum    // of the two radius, the circles touch or overlap    return squareDistance <= ((r1 + r2) * (r1 + r2))}

As you can see, the formula is tweaked a bit. Multiplication is much faster than getting the square root with
Math.sqrt() so the distance is calculated without getting the root and the sum of the radii is multiplied by itself. The outcome stays the same, but the performance is better.


Original Link: https://dev.to/ahmadcod/collision-detection-in-2d-game-development-with-javascript-47ao

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To