Frage

I am currently working on a LibGDX project in java and i was wondering how to detect mouse over shapes that aren't rectangles or circles. Let's say for example i have a spaceship. While rendering it you will have sprite that is a square and inside that square you have the spaceship. The problem is that the spaceship isn't a square so you will have blank space around edges of that sprite (most likely that blank space will be transparent so it won't cause any troubles over background or other scene objects). How do you detect mouse over the spaceship not the entire square? Is there any method?

War es hilfreich?

Lösung

There are several methods for making hit detection more precise.

Rectangles

First, I recommend you ignore the issue and use a rectangle slightly smaller or larger than the actual object (depending on if you want the 'hit' to be easier or harder). If there are gameplay problems, then you can make it more precise.

+----+
|    |
|    |
+----+

Multiple Rectangles

Once you've got support for a rectangle that is different from the rectangle used to draw the sprite, then you can get into breaking the space down more precisely. As the next level of approximation, you can subdivide the space in smaller parts (e.g., use several rectangles or a rectangle and a triangle).

+-+
| |++
| |++
+-+

Non-rectangles

Point-in-triangle tests are pretty quick (see Intersector.pointInTriangle, and actually lots of other useful methods in there). So you could represent your space ship by a rectangle for the base, and a triangle for the tip.

+-+
| |\
| |/
+-+

It often makes sense to 'nest' more complicated hit detection (so you have a big coarse box around the object, and only if that 'hits' do you check the more precise constraints to see if the location is within those bounds).

Pixels

In systems (not OpenGL!) where video memory is readable, and your game has a more direct knowledge of the pixels on the screen, you can test the alpha channel of an object (or even build a special 1-bit texture representing the transparent-or-notness) to detect if a particular click point is "inside" the object or not. This is really tough in OpenGL because the pixels on screen are rather abstracted. (Its not impossible, of course, but I think that's a different question, and one I don't know the answer to.)

So, most OpenGL-based games (I would guess) use abstract geometry (rectangles, triangles, circles, etc) to represent the object, and compute hit-or-not based on that, and not via texture pixels.

See also https://gamedev.stackexchange.com/questions/30866/collision-detection-with-non-rectangular-images

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top