1
\$\begingroup\$

This question already has an answer here:

I have a problem with collision detection in a 2D Java game.

Normally, what I would do is create a getBounds() method for an object that can collide with other objects. This method would return a new Rectangle(x,y,width,height), where x and y are the coordinates for the top-left corner of the sprite, and width and height are the width and height of the sprite.

But in the game I'm currently working on, there is a "tank" controlled by the user. The sprite of this tank rotates as long as the player holds one of the left or right arrow buttons. In other words, it can rotate to any angle. The tank's sprite is a rectangle.

So I can't simply do what I always do in this case.

How can I detect collision with this kind of sprite? Thanks

\$\endgroup\$

marked as duplicate by bobobobo, Seth Battin, Josh Jan 6 '14 at 0:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3
\$\begingroup\$

The simplest way to handle rotating 2D collisions is to use circles instead of rectangles. For most practical purposes, circles are a good approximation, simple to implement, and nobody will be able to tell the difference anyway. Two objects are colliding if the distance between the centres (using Pythagorean theorem) is less than the sum of the radiuses.

\$\endgroup\$
0
\$\begingroup\$

I agree with the other answer, to use circles as the simplest approach, although it only works with roughly square/circular objects. One alternative though would be to actually draw the objects and check for overlap, this gives pixel-perfect collision detection.

Give all "shootable" objects a unique id and have a buffer representing the screen. Render into the screen buffer the id of the object for the position it is in. I.e. if the Tank is 1 write a 1 in each location it occupies. If an enemy is 3 write a 3 there.

Once your scene is drawn then as your bullet moves check the stored value of the spaces it occupies (and spaces it moves through if it is moving fast enough that tunnelling is an issue). The number found is the id of the object you hit, 0 means continue. (Don't write bullets to that buffer unless you want them to hit each other).

\$\endgroup\$
  • \$\begingroup\$ Or use both methods. First use the circle method which is faster and if it returns true proceed with the drowing method to eliminate the slightest chance of error. This approach is good if you have to check many objects. \$\endgroup\$ – Gus Jan 5 '14 at 18:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.