# Best way to check collision for many elements

## Recommended Posts

Hi, i am curious what is best way to make collision. At this moment I make it this way: i have all elements with collision in an array and i iterate through it and calculate distance this way:

let dx = this._enemies[i].cords.x - this._players[y].cords.x;
let dy = this._enemies[i].cords.y - this._players[y].cords.y;
let distance = Math.sqrt(dx * dx + dy * dy);

if(distance < 100) {
//collision
}

This calculations make a sphere. We can do it this way to get a square or rectangle:

if(Math.abs(sprite1.x - sprite2.x) < 100 && Math.abs(sprite1.y - sprite2.y) < 10) {
//collison
}

I think this is not the best method, because lets imagine we have 1000 things with collision. We have to calculate their distance 1000x1000 = 1000000 times per frame.

My second thought is a 2d array that pretends to be map. If object is on x=200 and y=200 we can assign it like this map[200][200] = 1. And then another object check is that place is free (there will be 0 then). Its good when the object is 1 pixel wide and high. For larger objects it could be harder to implement.

How are you doing this?

Edited by newBie here
##### Share on other sites

We are lazy. We use a physics engine  (or collision library).

Wikipedia is quite enlightening. Optimization is done mostly through pruning and partitioning.

##### Share on other sites

Make some kind of a grid algorithm  PixiJS doesnt have anything in the package, we dont handle collisions. Grid usually is coded by users themselves.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.