彩音 - Adobe AIR - 研究室:XION -Adobe AIR-laboratory
短形領域の衝突 containsPoint()、containsRect()、intersects()

containsPoint() は点と領域を比較する。指定の点が短形領域の中に入っているときtrueになる。containsRect() と intersects() は領域同士を比較する。containsRect() は領域の中に別の領域が完全に入っているとき true になり、intersects() は領域と別の領域が交差しているとき true となる。
以下の例は短形領域 rect1、rect2、rect3 にマウスが入っているかどうかを containsPoint() を使い調べている。領域にマウスが入っていたら領域を囲むboxスプライトを表示し、マウスが領域からでたらboxスプライトを消す。


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="600" height="256" initialize="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var container:UIComponent = new UIComponent();
private var rect1:Rectangle = new Rectangle(100, 50, 200, 100);
private var rect2:Rectangle = new Rectangle(320, 20, 160, 100);
private var rect3:Rectangle = new Rectangle(360, 120, 150, 80);
private var rectList:Array = [rect1, rect2, rect3];
private var box:Sprite = new Sprite();
private function init():void {
addChild(container);
box.graphics.lineStyle(1, 0xff0000);
box.graphics.drawRect(0, 0, 100, 100);
container.addEventListener(Event.ENTER_FRAME, enterFrame);
}
private function enterFrame(event:Event):void {
var mousePoint:Point = new Point(application.mouseX, application.mouseY);
var isHit:Boolean = false;
for each (var hitzone:Rectangle in rectList) {
if (hitzone.containsPoint(mousePoint)) {
isHit = true;
box.x = hitzone.x;
box.y = hitzone.y;
box.width = hitzone.width;
box.height = hitzone.height;
container.addChild(box);
break
}
}
if ((contains(box)) && (isHit != true)) {
container.removeChild(box);
}
}
]]>
</mx:Script>
</mx:Application>

索引