1
因此我應該爲大學項目做一個落石遊戲的Javascript版本。 玩家控制一個矩形,該矩形應該從左向右移動而不會被落下的物體擊中。達到每一方都會提高得分,而得分會降低。遊戲結束在0點。使用Javascript進行碰撞檢測Falling Rocks遊戲
我似乎被卡在碰撞檢測部分。我試圖用每個對象的座標作爲碰撞的標準,但到目前爲止,我什麼也沒做。如果有人可以查看我做錯了什麼,我會非常感激。
玩家區塊的圖像大小爲x = 30px,y = 15px,而落下的物體爲15x15像素。
全部到目前爲止的代碼:
//canvas setup
var canvas = document.createElement("canvas");
canvas.style.background = "white";
canvas.style.height = "95%";
canvas.style.width = "99%";
document.body.appendChild(canvas);
canvas.style.border="1px solid black";
var ctx = canvas.getContext("2d");
// block image
var blockImg = new Image();
var t;
var block=
{
blockSpeed : 0
}
block.x=0;
blockImg.style.height=15;
blockImg.style.width=30;
blockImg.src = "squareche.jpg";
//draw block
blockImg.onload = function()
{
ctx.drawImage(blockImg, block.x,canvas.height-15);
}
function drawBlockProgress(pos)
{
ctx.drawImage(blockImg, block.x, canvas.height-15);
}
//Background image
var bckg = new Image();
bckg.src = "background.png";
function drawBackground()
{
ctx.drawImage(bckg, 0, 0);
}
//score
function drawScore()
{
ctx.font = "14px Times New Roman";
ctx.fillText("Score: " + score, 230, 25);
}
//score, position, and a bool flag for getting points on reaching either end
var score=50;
var pos = 0;
var flag = true;
//left and right keypush event handlers
document.onkeydown = function(event){
if(event.keyCode==39)
{
pos+=10;
block.x=block.blockSpeed+pos;
if(pos>=270)
{
if(flag)
{
flag=!flag;
score+=10;
}
pos=270;
block.x=270;
drawBlockProgress(pos);
}
else
{
drawBlockProgress(pos);
}
}
else if(event.keyCode == 37)
{
pos-=10;
block.x=block.blockSpeed+pos;
if(pos<=0)
{
if(!flag)
{
flag=!flag;
score+=10;
}
pos=0;
block.x=0;
drawBlockProgress(pos);
}
else{
drawBlockProgress(pos);
}
}
}
//set up the falling rocks
var imgRocks;
var x=0;
var y= 0;
var totalRocks = 10;
var rocks=[];
var speed = 0.2;
//generate the falling objects
function draw()
{
for(var i=0;i<totalRocks;i++)
{
drawBackground();
drawBlockProgress(pos);
drawScore();
ctx.drawImage(rocks[i].image, rocks[i].x, rocks[i].y);
rocks[i].y+=rocks[i].speed;
if(rocks[i].y > canvas.height-15)
{
rocks[i].y=-17;
rocks[i].x=Math.floor(Math.random()*300 + 1);
}
//collision check
if(block.x <= (rocks[i].x + 15)
&& rocks[i].x <= (block.x + 30)
&& block.y <= (rocks[i].y + 15)
&& rocks[i].y <= (block.y + 15))
{
// rocks[i].y=-15;
// rocks[i].x=Math.floor(Math.random()*300 + 1);
score -=10;
// if(score == 0)
// {
// break;
// clearInterval(t);
// alert("Game Over Dude !");
// window.close();
// }
}
}
}
function start()
{
for (var i = 0; i < totalRocks; i++) {
var fallingRock = new Object();
fallingRock["image"] = new Image();
rocksImg = new Image();
rocksImg.src = "rocks.jpg";
fallingRock.image.src = rocksImg.src;
fallingRock["x"] = Math.floor(Math.random() * 200 + 1);
fallingRock["y"] = Math.floor(Math.random() * 100 + 1);
fallingRock["speed"] = speed;
rocks.push(fallingRock);
t = setInterval(draw,10);
}
}
start();
您的碰撞檢測的代碼是好的,如果你在正確的信息發送。儘管(對不起),您在其他代碼中遇到了很多問題。 – markE
哦,那麼,任何啓動提示將受到歡迎呢? –