我是JavaScript的新手(刚开始在学校使用它),我一直在寻找让这个程序在课堂上完成。出于某种原因,我不能让它正常工作(无论我目前正在做什么)我试图用一组Missle对象填充一个Player对象......在将我的代码切换到这个对象的使用之前,我是能够显示" missles"但现在我被卡住了。
我只是放置了必要的代码:
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";}
答案 0 :(得分:1)
您的播放器应该有几个导弹,您使用数组表示:
this.missles = new Array();
使用数组时,必须循环(使用例如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) {
// ...