1

I'm writing a little 2D android game based on the SurfaceView Object, so I draw my whole game on a canvas. I designed a ball as a png and draw it on the canvas with this method:

canvas.drawBitmap(bmp, posX, posY, null);

Now my problem is that I do not know how I can receive touch events for this ball. My png is 64x64 pixel but the ball is only 32x32 pixel and in the middle of the image. I only want to receive touch events if the ball (32x32) is touched and not the bitmap (64x64). How can I do this? I can register an OnTouchListener for the SurfaceView but how can I detect the ball touch?

An other problem is that a ball is a simple object. What if I have some unregular objects which are not describeable through a radius or something else? Do I use the right "technology" with pngs at all for building controls for a canvas or is there a better/easier way?

That is a typical problem for me on all platforms (JS, Android, iOS) and I do not know the best way to solve it. That's why I used some other tags for this question. Isn't there a cross-platform solution so I can solve this problem forever?

gromiczek
  • 2,970
  • 5
  • 28
  • 49
Cilenco
  • 6,951
  • 17
  • 72
  • 152

2 Answers2

0

You can't get touch events for a bitmap on a canvas. You'll get touch events for the view. Then, based on the x,y coordinates of the touch, you have to determine what was touched.

In the case of a complex shape, you may check whether the corresponding bitmap pixel is transparent. But for practical purposes it may be enough to simply check that the touch is within some small distance of the center of the bitmap.

Rémi
  • 3,705
  • 1
  • 28
  • 39
0

Just an idea to help along as I have a game similar. What I did was in javascript capture mouse input. Than with that do a collision detection of the object you want, have the object's width and height be used for the test based on it's location. So if the users clicks/touches anywhere on the canvas have it check to see if fits within the object(s) area on the canvas.

canvas.addEventListener('mousemove', function(evt) {
    mousePos = getMousePos(canvas, evt);
  }, false);

function collides(a, b) {
          return a.x < b.x + b.width &&
            a.x + a.width > b.x &&
            a.y < b.y + b.height &&
            a.y + a.height > b.y;
        }

Edit

For logic with your circle: Circle Collision Detection HTML5 Canvas

"What if I have some unregular objects which are not describeable through a radius or something else?"

If your objects are irregular and need a different shape for collision detection that couldn't be solved with a circle or a box, take a look at this question: Collision detection of irregular shapes and something I found here, but neither looks to be a clear solution. What I would do is pick a circle or box that was best fit for the object but not sure how illregular your objects can get.

Community
  • 1
  • 1
fassetar
  • 615
  • 1
  • 10
  • 37