Java Reference
In-Depth Information
To find the current location of the Sprite 's reference pixel in its containing coordinate
system, use getRefPixelX() and getRefPixelY() . Don't get confused: defineReferencePixel()
accepts coordinates relative to the Sprite 's origin, while getRefPixelX() and getRefPixelY()
return values relative to the Sprite 's container. It's also possible to set the position of the
Sprite based on its reference point. You already know you can set the position of the Sprite 's
upper-left corner using the setPosition() method that is inherited from Layer , but the following
method sets the current position of the Sprite 's reference point:
public void setRefPointPosition(int x, int y)
This is more convenient than it might appear at first, as it allows you to place the reference
point at a specific position, regardless of the current transformation.
Handling Collisions
Sprite provides methods to answer critical questions that come up in games—did the bullet
hit the spaceship? Is Dr. Quatsch standing in front of the door?
The Game API supports two techniques for collision detection:
1.
The implementation can compare rectangles representing a sprite and another sprite.
A collision has occurred if the rectangles intersect. This is a quick way to test for collisions,
but it may produce inaccurate results for nonrectangular shapes.
2.
The implementation can compare each pixel of the sprite and another sprite. If an
opaque pixel in the sprite overlaps an opaque pixel in the other sprite, a collision has
occurred. This technique involves more computation but produces a more accurate result.
A Sprite has a collision rectangle that is used for collision detection. It is defined in the
coordinate system of the Sprite itself, like the reference pixel. By default, the collision rectangle
is located at 0, 0 and is the same width and height as the Sprite . You can change the collision
rectangle using this method:
public void defineCollisionRectangle(int x, int y, int width, int height);
The collision rectangle serves two purposes. If pixel-level collision detection is not used,
the collision rectangle is used to determine collisions. If pixel-level collision detection is used,
then only pixels inside the collision rectangle are examined.
Sprite is capable of detecting collisions with other Sprite s, TiledLayer s, and Image s.
public final boolean collidesWith(Sprite s, boolean pixelLevel)
public final boolean collidesWith(TiledLayer t, boolean pixelLevel)
public final boolean collidesWith(Image image,
int x, int y, boolean pixelLevel)
The semantics of each method are subtly different, as described in Table 14-2.
Search WWH ::




Custom Search