我想製作一個遊戲,其中壞人在飛機上飛行,你必須嘗試躲閃它們。我設法編寫了飛機的控制,以及如何將壞人加入/移動到舞臺上。我想知道如何編碼碰撞檢測,以便如果飛機被壞人擊中,我會被帶到「遊戲結束」屏幕。如何添加碰撞檢測
import flash.utils.Timer;
import flash.events.TimerEvent;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var baddies:Array = new Array();
var baddieSpeed:int = 15;
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
//deg2rad = Math.PI/180;
//rad2deg = 180/Math.PI;
plane.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_2);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_2);
function fl_MoveInDirectionOfKey_2(event:Event)
{
if (upPressed)
{
plane.y -= 8;
}
if (downPressed)
{
plane.y += 8;
}
if (leftPressed)
{
plane.x -= 8;
}
if (rightPressed)
{
plane.x += 8;
}
}
function fl_SetKeyPressed_2(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed_2(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
}
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
function addBaddie(evt:TimerEvent):void {
var baddie:Baddie = new Baddie();
baddie.x = - baddie.width
baddie.y = Math.random() * stage.stageHeight;
baddie.angle = getAngle(baddie.x, baddie.y, plane.x, plane.y);
baddie.rotation = getAngle(baddie.x, baddie.y, plane.x, plane.y);
baddie.speed = baddieSpeed
addChild(baddie);
baddies.push(baddie);
}
var baddieMover:Timer = new Timer(40);
baddieMover.addEventListener(TimerEvent.TIMER, moveBaddies);
baddieMover.start();
var counter:int = 0;
function moveBaddies(evt:TimerEvent):void {
for (var i:int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
}
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI/180);
}
function rad2deg(rad:Number):Number {
return rad * (180/Math.PI);
}
function getAngle(x1:Number, y1:Number, x2:Number, y2:Number):Number {
var radians:Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}