我应该在这里放一些代码让我的船停留在舞台上? 当我按下按键时,我的船离开了舞台,它走得太远了。如何让它碰到墙壁并让它留在舞台上?
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Ship extends MovieClip{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
function Ship(){
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
}
function kill(){
var explosion = new Explosion();
stage.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", move);
this.visible = false;
Game.gameOver();
}
function takeDamage(d){
health -= d;
if(health<=0){
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
}
function move(e:Event){
shootLimiter += 1;
if(Key.isDown(Keyboard.D)){
this.x = this.x + velocity;
}
if(Key.isDown(Keyboard.A)){
this.x = this.x - velocity;
}
if(Key.isDown(Keyboard.W)){
this.y = this.y - velocity;
}
if(Key.isDown(Keyboard.S)){
this.y = this.y + velocity;
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8){
shootLimiter = 0;
var b = new Bullet();
stage.addChild(b);
b.x = this.x + 40;
b.y = this.y + -25;
}
if(shield.visible == true){
shield.alpha -= 0.0005;
if(shield.alpha == 0){
shield.visible = false;
shield.alpha = 1;
}
}
}
}
}
答案 0 :(得分:0)
您的代码很难修复,但我会以伪为单位给您答案,因此您可以考虑如何实现它以适应您的项目。你的船离开了框架,因为它没有停止的概念。让我们说船舶的x和y坐标是从精灵的左上角开始的,就像在动作中一样,然后,每当你的船向左移动时,你必须考虑以下事项:
if(Key.isDown(Keyboard.A)){
var futureX:Number = this.x - velocity;
if (futureX <= 0){ //your ship has reached the left border of the screen
this.x = 0;
} else {
this.x = futureX;
}
}
当您检查屏幕的右边界或下边框时,事情会变得复杂一些,因为您需要在计算中考虑舞台的大小和精灵的大小:
if(Key.isDown(Keyboard.S)){
var futureY:Number = this.y + velocity;
if (futureY + this.height >= Stage.stageHeight){
this.y = Stage.stageHeight - this.height;
} else {
this.y = futureY;
}
}
在此之后,顶部和右边界的解决方案是微不足道的。