【发布时间】:2015-11-29 05:28:32
【问题描述】:
我的 JavaScript 课程有一个项目到期,但我不知道如何进行命中测试!我一直在寻找大约 3 周的时间,但没有找到我想要的东西......虽然我想出了几个不同的想法,但它们都不起作用。
function hitTest() {
for (var i = 0; i < fruit.length; i++){
for (var j = 0; j < catLoc.length; j++){
distance = Math.pow((catLoc[j][0] - fruit[i][0]), 2) +
Math.pow((catLoc[j][1] - fruit[i][1]), 2);
distance = Math.sqrt(distance);
if (distance < r){
alive = false;
if (!alive) {
alert("you loose");
}
}
}
}
}
function hitTest1(){
for (var i = 0; i < catLoc.length; i++) {
for (var j = 0; j < fruit.length; j++) {
if (fruit[j] == (catLoc[i][0] && catLoc[i][1])){
alive = false;
if (!alive) {
alert("you loose");
}
}
}
}
}
这是我试图承认彼此存在的原因:
function FruitGenerator() {
// select a random type for this new object
var F;
if (Math.random() < 0.50) {
F = "blue";// blueberries
} else {
F = "purple";//grapes
}
// create the new object
var object = {
type: F,
//amount off side of canvas
x: Math.floor(Math.random() * (width - s)),
//starting line
y: spawnLineY,
};
fruit.push(object);
}
function spawnFruit() {
// get the elapsed time
var time = Date.now();
// see if its time to spawn a new object
if (time > (lastSpawn + spawnRate)) {
lastSpawn = time;
FruitGenerator();
}
requestAnimationFrame(spawnFruit);
// draw the line where new objects spawn
ctx.beginPath();
ctx.moveTo(0, spawnLineY);
ctx.lineTo(canvas.width, spawnLineY);
ctx.stroke();
// makes fruit fall
fruitFall();
}
function fruitFall(){
//moves the fruit down the screen
for (var i = 0; i < fruit.length; i++) {
object = fruit[i];
object.y += fruitFallSpeed;
ctx.beginPath();
ctx.arc(object.x, object.y, r, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = object.type;
ctx.fill();
}
}
我想让这些下落的圆圈撞到我画的一只猫,它基本上只是一个 100、100 的盒子,上面有猫的胡须、眼睛和耳朵,但我只是想让它承认这里的盒子是我用来移动它的东西画布并存储其 x、y 坐标
function moveThatCat(){
if (x > 500) {
x = x;
} else if (rightKey) x += 5;
if (x < 0) {
x = x;
} else if (leftKey) x -= 5;
if (y < 40) {
y = y;
} else if (upKey) y -= 5;
if (y > 440) {
y=y;
} else if (downKey) y += 5;
//clearing the array catLoc and adding the new X, Y locations
catLoc.splice(0, catLoc.length);
catLoc.push(x, y);
}
x=250 y=400 and the canvas = width="600" height="540".
【问题讨论】:
标签: javascript canvas hittest