Square hittest
♥0 |
Line 101 |
Modified 2012-12-23 00:50:08 |
MIT License
archived:2017-03-20 07:57:33
ActionScript3 source code
/**
* Copyright Thumasz ( http://wonderfl.net/user/Thumasz )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/i90L
*/
package {
////////////////////////////////////////////////////
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.geom.*;
public class FlashTest extends Sprite
{
private var sq0:Square;
private var sq1:Square;
public function FlashTest()
{
sq0 = new Square(0x666666, 150);
addChild(sq0);
sq0.x=sq0.y=150;
//
sq1 = new Square(0x000000, 50);
addChild(sq1);
sq1.x=sq1.y=50;
sq1.buttonMode=true;
//
sq0.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
sq0.addEventListener(MouseEvent.MOUSE_UP, mUp);
sq1.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
sq1.addEventListener(MouseEvent.MOUSE_UP, mUp);
addEventListener(Event.ENTER_FRAME, update);
}
public function update(e:Event):void{
switch(checkCollision(sq0, sq1)){
case 0:
sq0.setColor(0xCCCCCC);
break;
case 1:
sq0.setColor(0x000000);
break;
case 2:
sq0.setColor(0xFF0000);
break;
case 3:
sq0.setColor(0x00FF00);
break;
case 4:
sq0.setColor(0x0000FF);
break;
case 5:
sq0.setColor(0xFF00FF);
break;
}
}
public function checkCollision(a:Square, b:Square):int{
var aMin:Point = new Point(a.x, a.y);
var aMax:Point = new Point(a.x + a.width, a.y + a.height);
var bMin:Point = new Point(b.x, b.y);
var bMax:Point = new Point(b.x + b.width, b.y + b.height);
var left:Number = bMin.x - aMax.x;
var right:Number = bMax.x - aMin.x;
var top:Number = bMin.y - aMax.y;
var bottom:Number = bMax.y - aMin.y;
if(left > 0) return 0;
if(right < 0) return 0;
if(top > 0) return 0;
if(bottom < 0) return 0;
var returnCode:Point = new Point();
returnCode.x = (Math.abs(left) - right) * a.width;
returnCode.y = (Math.abs(top) - bottom) * a.height;
var temp:int = 0;
if(returnCode.x > 0){
//Hits left
temp = 2;
}else{
//Hits right
temp = 3;
}
if(returnCode.y > 0){
//Hits top
if(returnCode.y > Math.abs(returnCode.x)){
temp = 4;
}
}else{
//Hits bottom
if(returnCode.y < -Math.abs(returnCode.x)){
temp = 5;
}
}
return temp;
}
public function mDown(e:MouseEvent):void{
e.target.startDrag();
}
public function mUp(e:MouseEvent):void{
e.target.stopDrag();
}
}
////////////////////////////////////////////////////
}
import flash.display.*;
internal class Square extends Sprite{
private var _size:int;
public function Square(color:uint,size:int){
graphics.beginFill(color);
graphics.drawRect(0, 0, size, size);
_size = size;
}
public function setColor(color:uint):void{
graphics.clear();
graphics.beginFill(color);
graphics.drawRect(0, 0, _size, _size);
}
}