Hi there, I was wondering if there was a more accurate way to detect collisions using actionscript3. I’ve made a simple helicopter-like side-scroller, and the collision detection isn’t working very well. Basically, the red rectangle (the helicopter) will detect a collision when it travels downward to hit an obstacle. If it’s traveling upward or sideways, the collision detection gets a bit funky. Right now I’m using the hitTestPoint command, if anyone else knows a better way to do it, I’d be very appreciative. I’ll attach the .fla and its source code.
package
{
import flash.display.MovieClip
import flash.events.Event
import flash.events.KeyboardEvent
public class DocumentMain extends MovieClip
{
public var _startMarker:StartMarker;
public var _player:Player;
public var _boundaries:Boundaries;
private var _vx:Number;
private var _vy:Number;
public function DocumentMain():void
{
// assign default values
_vx = 0;
_vy = 0;
_startMarker.visible = false;
// set focus for keyboard input
stage.focus = stage;
// add event listeners
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
}
private function enterFrameHandler(e:Event):void
{
// gravitate the player
_vy += 1;
// move the player
_player.x += _vx;
_player.y += _vy;
// process collisions
processCollisions();
// scroll the stage
scrollStage();
}
private function keyDownHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37:
_vx = -7;
break;
case 38:
_vy = -10;
break;
case 39:
_vx = 7;
break;
default:
}
}
private function keyUpHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37:
case 39:
_vx = 7;
break;
default:
}
}
private function processCollisions():void
{
// when player is falling
if (_vy > 0)
{
// respawn if player fell off the stage
if (_player.y > stage.stageHeight)
{
_player.x = _startMarker.x;
_player.y = _startMarker.y;
_boundaries.x = 0;
_boundaries.y = 0;
_vy = 0;
}
if (_boundaries.hitTestPoint(_player.x, _player.y, true))
{
_player.x = _startMarker.x;
_player.y = _startMarker.y;
_boundaries.x = 0;
_boundaries.y = 0;
_vy = 0;
}
// otherwise, process collisions with boundaries
}
}
private function scrollStage():void
{
_boundaries.x += (stage.stageWidth * 0.5) - _player.x;
_player.x = stage.stageWidth * 0.5;
}
}
}