【发布时间】:2016-05-20 11:18:41
【问题描述】:
我制作了这个小游戏来为我的网络编程考试做准备,但它并没有完全奏效,而且我被卡住了。
我基本上有一个对象 Star ,它的 isCaught 属性是标准的 false,当它与另一个对象(女巫)碰撞时变为 true。
我希望我的程序始终循环遍历我的 Star 对象数组,并检查数组中的每个元素是否都已被捕获 (isCaught = true),如果是,它应该提醒用户。 但是,它只返回 false(并且只返回 3 次)。
如果对象没有被捕获并到达屏幕的末尾,我也尝试从数组中删除它们,但是我会遇到索引问题(这是注释掉的部分)。
我可能正在做一些非常愚蠢非常错误的事情,但我找不到它。 代码如下:
function Star(x, y, vy){
this.x = x;
this.y = y;
this.vy = vy;
this.isCaught = false;
var starImg = new Image();
starImg.src = 'images/star.png';
$(starImg).load(function(){
});
this.drawStar = function(){
ctx.drawImage(starImg,this.x,this.y,20,20);
//context.beginPath();
}
}
function Witch(){
this.x = 10;
this.y = 300;
var witchImg = new Image();
witchImg.src = 'images/witch2.png';
$(witchImg).load(function(){
});
this.drawWitch = function(){
ctx.drawImage(witchImg,this.x,this.y,50,50);
}
}
var canvas;
var ctx;
var speed = 33;
var starsAmount = 6;
var stars = [];
var witch = new Witch();
$(function(){
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
$("body").mousemove(function(arg){
//witch.y = arg.pageY;
witch.x = arg.pageX;
});
for(var i=0;i<starsAmount;i++){
stars.push(new Star(Math.floor(Math.random()*canvas.width)+50,10,2));
}
Animate();
});
function Animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
var countCaught = 0;
for (var i = 0; i < stars.length; i++){
stars[i].y += stars[i].vy;
stars[i].drawStar();
witch.drawWitch();
}
//collision detection
for(var i=0; i<stars.length; i++){
var distanceX = (stars[i].x+10)-(witch.x+25);
var distanceY = (stars[i].y+10)-(witch.y+25);
var distance = Math.sqrt((distanceX*distanceX)+(distanceY*distanceY));
if(distance < 35){
stars[i].x = Math.floor(Math.random()*canvas.width);
stars[i].y = -20;
stars[i].vy += 1;
stars[i].isCaught = true;
}
var allCaught = checkCaught();
console.log(allCaught);
if(allCaught == true){
("You've lost!");
}
//if the stars reach the end of the screen and they are not caught, delete them from the array
/*
if((stars[i].y+10) == canvas.height && stars[i].isCaught == false){
console.log(stars[i].y);
stars.splice(i,1);
console.log("say something im giving up on you" + i);
}
console.log("array length " + stars.length);
*/
}
setTimeout(Animate,speed);
}
function checkCaught(){
var allCaught = true;
for(var i=0; i<stars.length; i++){
if(stars[i].isCaught == false){
allCaught = false;
}
else{
allCaught = true;
}
}
return allCaught;
}
提前致谢!
【问题讨论】:
-
问题出在你的 for 语句中。如果有未捕获的,只需添加一个休息时间。喜欢@Nils 的回答
-
和
if(allCaught == true){ ("You've lost!"); }我认为你应该改变这个 -
主要问题似乎是,您有时会错过一颗飞到画布外的星星,因为您使用 +50px 对其进行初始化 - 这在某些情况下可能导致将它们绘制到画布外。因此你永远抓不到他们。
-
@Nils 我明白了,我现在删除了 +50。谢谢
-
@jackpop 会做的谢谢^_^
标签: javascript function object