简体   繁体   中英

HTML5 Canvas: adding collision to constantly drawn images

I am making a Tron game in HTML5 canvas and I'm running into some trouble getting the tails of the bikes to cause collision. I have collisions with walls and other players but since the tail is constantly being created I can't figure out how to add a collision trigger.

Here is what I have so far: https://github.com/ewbutterfield/Tron
Demo site: http://canvas-tron.gopagoda.com/

Before you draw your new line segment and player you can do a simple check of the pixel in the new position:

var pix = ctx.getImageData(x, y, 1, 1).data;  /// location to sample a pixel from

/// check that it is the color of the background (here transparent)
if (pix[3] !== 0] {
    /// some collision happened...
 }

You can simple check for a color instead of transparancy if you want to use that (or set the background of the canvas using CSS instead).

Next is to check if you hit the line or a player. You can do that by using different colors for the two or else you need to record the positions the players are moving to and check with that array when you got a "pixel hit".

Note: it's important that you do the test before drawing the line and player or else you will sample that instead which of course gives you a hit every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM