Jcanvas layer collision

348 views Asked by At

I'm trying to make a function to detect if two layers collide. Using Jquery, jcanvas and HTML5 canvas

I'm building a sort of flight simulator where the player can ascend/descend to avoid hot airballons coming towards the player.

I need to detect if the plane is about to collide with the ballon layer.

I've tried checking the layers x/y position but that doesn't work so well since the hot airballon isn't squere shaped.

Imagine this:

      ______________               __
    /                \            / /       _
   /                  \      ___/__/_______/ /\
  |   Air ballon       |    /    Plane 1      /
  |                    |    \___\  \_______\ \
   \                  /          \  \       \/
    \                /            \__\
     \              /
      \            /                __
       \          /                / /       _
        \        /            ___/__/_______/ /\
         \      /            /    Plane 2      /
          \____/             \___\  \_______\ \
           |__|                   \  \       \/
           |__|                    \__\

In my current solution both planes will collide at the same time. I need plane 2 to collide later, when the plan actually collides with the air ballon basket

1

There are 1 answers

0
Philipp On BEST ANSWER

The problem you are having is usually referred to as collision detection.

The most common approach to collision detection is to abstract each object as a geometrical shape and then check if these shapes intersect. Common choices are either rectangles or circles, because checking these for intersection with each other is rather trivial.

Another approach is to use pixel-based collision detection. You draw the two objects you want to check on separate layers, and then you check the color-value of each pixels on both layers. When the alpha-values of both are > 0, you have a collision. The advantage is that it is very accurate, but the disadvantage is that it is quite CPU intense because you need to check so many pixels. To optimize the CPU load, you can combine it with the geometric method to reduce the amounts of pixels you need to check.

  1. define a rectangle around each object
  2. check if the rectangles intersect
  3. when they do calculate the intersecting area
  4. draw both objects to separate, empty, canvases
  5. get the pixel-data of the areas on both canvases with context.getImageData()
  6. Compare the alpha-value of the returned arrays. When the same pixel on both canvases is greater than 0, you have a collision.