Flash CS4 Professional ActionScript 2.0

hitTest (BitmapData.hitTest method)

public hitTest(firstPoint: Point, firstAlphaThreshold: Number, secondObject: Object, [secondBitmapPoint: Point], [secondAlphaThreshold: Number]) : Boolean

Performs pixel-level hit detection between one bitmap image and a point, rectangle or other bitmap image. No stretching, rotation, or other transformation of either object is considered when doing the hit test.

If an image is an opaque image, it is considered a fully opaque rectangle for this method. Both images must be transparent images to perform pixel-level hit testing that considers transparency. When you are testing two transparent images, the alpha threshold parameters control what alpha channel values, from 0 to 255, are considered opaque.

Availability: ActionScript 1.0; Flash Player 8

Parameters

firstPoint: Point - A point that defines a pixel location in the current BitmapData instance.

firstAlphaThreshold: Number - The highest alpha channel value that is considered opaque for this hit test.

secondObject: Object - A Rectangle, Point, or BitmapData object.

secondBitmapPoint: Point [optional] - A point that defines a pixel location in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object.

secondAlphaThreshold: Number [optional] - The highest alpha channel value that is considered opaque in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object and both BitmapData objects are transparent.

Returns

Boolean - A Boolean value. If there is a hit, returns a value of true; otherwise, false.

Example

The following example shows how to determine if a BitmapData object is colliding with a MovieClip.

import flash.display.BitmapData;
import flash.geom.Point;

var myBitmapData:BitmapData = new BitmapData(100, 80, false, 0x00CCCCCC);

var mc_1:MovieClip = this.createEmptyMovieClip("mc", this.getNextHighestDepth());
mc_1.attachBitmap(myBitmapData, this.getNextHighestDepth());

var mc_2:MovieClip = createRectangle(20, 20, 0xFF0000);

var destPoint:Point = new Point(myBitmapData.rectangle.x, myBitmapData.rectangle.y);
var currPoint:Point = new Point();

mc_1.onEnterFrame = function() {
    currPoint.x = mc_2._x;
    currPoint.y = mc_2._y;
    if(myBitmapData.hitTest(destPoint, 255, currPoint)) {
        trace(">> Collision at x:" + currPoint.x + " and y:" + currPoint.y);
    }
}

mc_2.startDrag(true);

function createRectangle(width:Number, height:Number, color:Number):MovieClip {
    var depth:Number = this.getNextHighestDepth();
    var mc:MovieClip = this.createEmptyMovieClip("mc_" + depth, depth);
    mc.beginFill(color);
    mc.lineTo(0, height);
    mc.lineTo(width, height);
    mc.lineTo(width, 0);
    mc.lineTo(0, 0);
    return mc;
}