Collision

Code Actionscript 2.0

Instance action

onClipEvent (load) {
speedx = 5;
speedy = 12;
}
onClipEvent (enterFrame) {
// square moves with speedx, speedy
this._x = this._x + speedx;
this._y = this._y + speedy;
// change direction, if outside borders
if ((this._x > 375) || (this._x < 25)) {
speedx = -1 * speedx;
}
if ((this._y > 375) || (this._y < 25)) {
speedy = -1 * speedy;
}
// if red hits black, something happens
if (this.hitTest(_parent.blacksquare)) {
trace("I am hit!");
this._xscale = 200;
this._yscale = 200;
} else {
this._xscale = 100;
this._yscale = 100;
}
}

Code Actionscript 3.0

addEventListener(Event.ENTER_FRAME, enterFrame); var speedx = 5; var speedy = 12; function enterFrame(event:Event) { // redsquare moves with speedx, speedy redsquare.x = redsquare.x + speedx; redsquare.y = redsquare.y + speedy; // change direction, if outside borders if ((redsquare.x > 375) || (redsquare.x < 25)) { speedx = -1 * speedx; } if ((redsquare.y > 375) || (redsquare.y < 25)) { speedy = -1 * speedy; } // if red hits black, something happens if (redsquare.hitTestObject(blacksquare)) { trace("I am hit!"); redsquare.scaleX = 2; redsquare.scaleY = 2; } else { redsquare.scaleX = 1; redsquare.scaleY = 1; } }

Description

One square moves continuously, while the other square remains put. If the two squares overlap, something happens. The function this.hitTest (redsquare.hitTestObject respectively) verifies, whether the red square has come into contact with the black square and performs a specified task as a result.

related to: Bouncing movement

Download

Right click: Flashfile AS 2.0 | Flashfile AS 3.0 | SWF-File


Share