您的位置:首页 > 其它

关于两个不规则图形的碰撞检测

2011-01-27 16:36 197 查看
今天研究了一下两个movieclip图形的碰撞,心得如下:

1.将两个要进行碰撞的movieclip存入两个bitmapdata中,使用bitmapdata.draw方法来分别获取这两个movieclip的图形信息,注意先用getRect获取可见图形的矩形区域,然后用matrix(1,0,0,1,-getRect.left,-getRect.top)来获取完整的图像信息

2.使用bitmapdata.hittest时的point一定要写对,要放到同一坐标系下进行比对

具体的程序结构如下

a. 名为hittest.fla文件中建两个mc,名称分别为star和base(star包含base,star的作用在于获取bitmapdata,而base的作用在于旋转),star绑定类star,base的mc中画一个不规则图形

b. hittest.fla文档绑定类hittest

c. hittest.as的内容

package {

import flash.display.MovieClip;

import flash.utils.Timer;

import flash.events.TimerEvent;

import flash.display.Bitmap;

import flash.geom.Rectangle;

import flash.utils.ByteArray;

import flash.display.BitmapData;

import flash.geom.Point;

public class hittest extends MovieClip {

private var setTimer:Timer;

private var star1:star;

private var star2:star;

public function hittest() {

// constructor code

star1 = new star(50);

star1.name = "star1";

star1.x = 150;

star1.y = 200;

addChild(star1);

star2 = new star(100);

star2.name = "star2";

star2.x = 310;

star2.y = 160;

addChild(star2);

setTimer = new Timer(50);

setTimer.addEventListener(TimerEvent.TIMER, this.hitcheck);

setTimer.start();

}

private function hitcheck(ent:TimerEvent) {

if(star1.bitmap == null || star2.bitmap == null) {

return;

}

else {

var star1point:Point = new Point();

var star1rect:Rectangle = star1.getRect(star1);

star1point.x = star1.x + star1rect.x;

star1point.y = star1.y + star1rect.y;

var star2point:Point = new Point();

var star2rect:Rectangle = star2.getRect(star2);

star2point.x = star2.x + star2rect.x;

star2point.y = star2.y + star2rect.y;

if(star1.bitmap.hitTest(star1point,1,star2.bitmap,star2point,1))

{

setTimer.stop();

star1.setTimer.stop();

star2.setTimer.stop();

}

}

}

}

}

d. star.as的内容

package {

import flash.display.MovieClip;

import flash.utils.Timer;

import flash.events.TimerEvent;

import flash.display.BitmapData;

import flash.geom.Rectangle;

import flash.geom.Matrix;

public class star extends MovieClip {

public var setTimer:Timer;

public var bitmap:BitmapData;

public function star(internum:int) {

// constructor code

setTimer = new Timer(internum);

setTimer.addEventListener(TimerEvent.TIMER, this.movenow);

setTimer.start();

}

private function movenow(ent:TimerEvent) {

//碰撞检测

var maprect:Rectangle = this.getRect(this);

bitmap = new BitmapData(maprect.width, maprect.height, true, 0);

bitmap.draw(this, new Matrix(1, 0, 0, 1, -maprect.left, -maprect.top));

this["base"].rotation++;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: