Thursday 29 January 2009

Day 11 - hitTestObject

I'm getting more confident writing basic functionality in classes. Got caught out by a few scope issues.

Got hitTestObject working quiet nicely. As you can see in the video when the blue square hits the red square the blue square stops. The method is called from the main class

blueClip.hitStuff(redClip);

Got better ways of doing this? Or want more explanation please comment.



This is the code for the main class

package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;

public class Main extends flash.display.Sprite{
private var blueClip:Rec;
private var redClip:Rec;
private var greenClip:Rec;
public function Main() {
blueClip= new Rec(300,50,0x66CCFF);
addChild(blueClip);
blueClip.go( -1);
redClip = new Rec(20, 50, 0xDC143C);
addChild(redClip);
redClip.go(1);
greenClip = new Rec(70, 50, 0x669900);
addChild(greenClip);
greenClip.go(1);
blueClip.hitStuff(redClip);
}
}
}


This is the code for the Rec class that draws the rectangles

package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;

public class Rec extends Sprite {
//private var movetimer:TimerEvent;
private var moveTimer:Timer=new Timer(10,0);
public function Rec(xPos:Number,yPos:Number,shapeColour:uint) {
graphics.beginFill( shapeColour , 0.5 );
graphics.drawRect( xPos , yPos , 20,20 );
graphics.endFill( );

}
public function go(speed:Number):void {
moveTimer.addEventListener(TimerEvent.TIMER,onTimer);
moveTimer.start();

function onTimer(e:TimerEvent):void{
x += speed;
e.updateAfterEvent();
}
}
public function hitStuff(clip:Rec):void {

addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame():void{
if (hitTestObject(clip)) {
moveTimer.stop();
trace("collision with " + clip.name);
}

}
}
}
}

No comments:

Post a Comment