0

我对 JavaScript 有点陌生(刚在学校开始使用它),我一直在四处寻找这个程序来完成课堂。出于某种原因,我无法让它正常工作(无论我目前正在做什么)我试图用一组 Missle 对象填充一个 Player 对象......在将我的代码切换到对象的这种使用之前,我是能够显示“导弹”,但现在我被卡住了。

我只放置我必要的代码:

function Player(){
    this.x = c.width/2;
    this.y = c.height-20;
    this.w = 50;
    this.h = 10;
    this.dx = 30;
    this.score = 0;
    this.missles = new Array();}

function Missle(x, y){
    this.x = x;
    this.y = y;
    this.dy = 10;
    this.w = 8;
    this.h = 8;
    this.visible = "false";}


function init1P(){
if (playing == "true"){
    player = new Player();
    animate1P();
}}

function animate1P(){
cntxt.clearRect( 0, 0, c.width, c.height );

cntxt.fillStyle="#000000";
cntxt.fillRect(0,0,c.width,c.height);

cntxt.fillStyle="#ffffff";
cntxt.font="34px Verdana";
cntxt.fillText(player.score, 10, c.height-10);  

cntxt.fillStyle="#ffffff";

cntxt.fillRect(player.x,player.y,player.w,player.h);

//cntxt.fillRect(comp.x,comp.y,comp.w,comp.h);

if ( player.missles.visible == "true" ) {
    cntxt.fillStyle = "#FF0000";
    cntxt.fillRect( player.missles.x, player.missles.y, player.missles.w, player.missles.h );
    //isHit();
    if ( hit == "false" ) {
        player.missles.y -= player.missles.dy;
        if ( player.missles.y <= 0 ) {
            player.missles.visible = "false";
        }
    }
}

// request new frame
if ( playing == "true" ) {
    requestFrame( function() { animate1P(); } );
}

//moveComp();
checkBoundaries(player);
//checkBoundaries(comp);
//isHit(player);
//isHit(comp);  }

function shoot() {
player.missles.push(new Missle(player.x + player.w/2, player.y + 10));
player.missles.visible = "true";
hit = "false";}
4

1 回答 1

1

你的玩家应该有几个导弹,你用一个数组来表示:

this.missles = new Array();

使用数组时,您必须循环(使用 eg for)将某些内容应用于每个元素。所以,player.missles.visible = "false"实际上只是在数组本身上设置一个属性,而不是在每个元素上。你必须这样做:

for(var i = 0; i < player.missles.length; i++) {
  player.missles[i].visible = "false";  // player.missles[i] is one item on each iteration
}

绘图也是如此:在循环中获取和更新每个导弹的数据:

for(var i = 0; i < player.missles.length; i++) {
  if ( player.missles[i].visible == "true" ) {
    // ...
}

另外,请注意 JavaScript 中有布尔值。你可以只使用true/ false,然后你可以直接使用if这样的:

if(player.missles[i].visible) {
  // ...
于 2012-09-07T16:58:47.843 回答