Jump to content

ignore transparent areas of sprite for overlap


lgrog
 Share

Recommended Posts

Hi,

I have a game where I kill the player if he jumps on one of the enemies using overlap.

The problem is that the sprite is square with transparent corners. this causes the player to die when he touches those corners (even though he didn't actually touch the image of the enemy)

Has anyone else had this problem?

any ideas how to solve it?

thanks.

Link to comment
Share on other sites

I think the best way would be to implement a proper collision detection algorithm, where you can define your own collision shapes that approximate the actual shapes of your sprites... then check if the collision shapes intersect. It is a bit complicated, but you can use pretty much any physics engine to do that.

 

Another way (which is simpler but much, much slower and potentially too slow on some devices and browsers) is to draw your sprites on small canvas objects, then get the image data out of the canvas objects (with context.getImageData()) and then for each pixel in the overlap area, check to see if both sprites have a non-transparent value.

Link to comment
Share on other sites

Checking overlap using circles rather than rectangles might look better and it's even easier/faster...

 

var dx = x2 - x1; // center coordinates of the 2 objects

var dy = y2 - y1;

var distance = Math.sqrt(dx * dx + dy * dy); // distance between the two

if( distance < collisionDistance ) {

  // hit!

}

 

Pixel-perfect collision tests will be much more CPU intensive. You're usually better off doing simplified shape hit tests. Alternately you could do a simplified hit test first, then do a more detailed hit test only if the simple hit test was true.

Link to comment
Share on other sites

thanks. great solutions.

I am going to try the circle method.

What sprites am I getting back in the overlap function? I couldn't find the documentation (I need the coordinates of the sprites that overlapped)

Link to comment
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...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...