QUICK NAVIGATOR
PRODUCTS
TECHNOLOGIES
DEVELOPMENT TOOLS
* News
* Java Media Framework
* Intel Animation for Java
* Intel Spatial Audio for Java
* Runtime Software License
* SDK Software License
* System Requirements
* Download Area
* Documentation Online
* Gallery
* General FAQ
* Support Information

[INTEL NAVIGATION HEADER]

Intel Animation for Java* Package Tutorial

Lesson 8: Detecting Sprite Collisions



This applet demonstrates how to detect when Sprites collide. By clicking the direction buttons for Elvis and Weeble you can initiate a collision. The task of detecting Sprite collisions is accomplished by using the following method provided by the Rectangle class:

public boolean intersection(Rectangle r)

Each sprite in the applet above is associated with a rectangle, which can then be used with the intersection method.

Boolean collision = WeebleRect.intersection(ElvisRect);

Further precision with Sprite collisions can be obtained by trimming the sides of the collision rectangles. The output view of each Sprite is the initial size of the collision rectangles.

Rectangle ElvisRect, WeebleRect;

Sprite Elvis, Weeble, Collision;

ElvisRect = Elvis.getOutputView();

WeebleRect = Weeble.getOutputView();

ELVIS_TRIM and WEEBLE_TRIM, in the code sample below, represent the width is pixels to shave off each side of the collision rectangles.

ElvisRect.x += ELVIS_TRIM;

ElvisRect.width -= 2*ELVIS_TRIM;

WeebleRect.x += WEEBLE_TRIM;

WeebleRect.width -= 2*WEEBLE_TRIM;

Finally, the "intersects" method is used to determine if a collision occurred.

if (WeebleRect.intersects(ElvisRect)) Collision.setVisibility(true); else Collision.setVisibility(false);

Previous Lesson Tutorial Contents  

View Source

 

This page was last updated on Feb 11th, 1997.

Legal Stuff

Free Web Hosting