# Perfect collision between 2 sprites

## Recommended Posts

Hi guys! I'm playing with pixi.js and trying to detect collisions between 2 srites. Currenly im using:

isIntersecting = function(r1, r2) {
return !(r2.x > (r1.x + r1.width)  ||
(r2.x + r2.width ) < r1.x ||
r2.y > (r1.y + r1.height) ||
(r2.y + r2.height) < r1.y);

}

But i need to make these more perfect because this function not work properly with rounded images...

Anyone got some better function?

Thanks guys!

##### Share on other sites

rounded images...

Do you mean rounded rectangles or circles?

##### Share on other sites

Do you mean rounded rectangles or circles?

Could be both, it's just an example. Imagine i'm using a plane image, it's not rectangle so my collison function isn't work good...

##### Share on other sites

You need to define a hit polygon for each sprite. There are several physic editors which will do that for you.

Also your current hitTest is not accurate.

The fastest hitTesting are rectangles and circles. For a circle you would test if the combined radii is bigger than the distance between both circles and for rectangles you would test if part of R1 is in R2 or part of R2 is in R1.

Polygon hitTesting is far more expensive.

##### Share on other sites

If you want want collision detection for any arbitrarily shaped image, you'll need to use a pixel-perfect algorithm, like this one:

http://www.playmycode.com/blog/2011/08/javascript-per-pixel-html5-canvas-image-collision-detection/

There might be more optimized algorithms out there that someone reading this post can tell us about.

However, for a high-performance game I'd suggest you just try and stick to rectangles and circle based collision detection if you can, because even a highly-optimized pixel-pefect algorithm will be slow.

##### Share on other sites

I'd just create hitPolygons. Either on runtime or if possible preruntime.

## 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.