newBie here

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 this post


Link to post
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.