【发布时间】:2014-12-24 21:53:10
【问题描述】:
所以我的学校作业项目快结束了,我只是错过了两件我似乎无法弄清楚的主要事情:
1.如何为间隙生成具有随机位置的管道障碍物,以便鸟可以飞过(尝试使用更改管道 div 的 css 'right' attr 用于间隙位置的函数),并移除当它离开屏幕底部时的管道。 (顺便说一句,它是一个倒飞鸟游戏……)
2.其次,我需要碰撞检测功能的帮助,以便我知道游戏何时结束(这不太重要,因为我认为在解决第一个问题后我可以弄清楚)
$(document).ready(function(){
//Variables
var screenWidth = $(window).width();//Screen width
var screenHeight = $(window).height();//Screen height
var birdWidth = $("#bird").width();//bird width
var y = 0;//Background y position
var astY = 0;//Pipe position
var bird = {//bird properties
goingLeft: false,
goingRight: false,
lspeed: 0,
rspeed: 0,
maxSpeed: 10
};
setBirdPosition(screenWidth/2 - birdWidth/2, screenHeight/1.3 - birdWidth/2);
startBackgroundMovement();
spawnPipe();
//Start move the screen
function startBackgroundMovement(){
setInterval(function()
{
y+=1;
$('body').css('background-position-y',y + 'px');
}, 10);
}
//bird starting position
function setBirdPosition(posX, posY) {
$("#bird").css("left", posX);
$("#bird").css("top", posY);
bird.position = posX;
}
(function birdLoop() {
if (bird.goingLeft) {
bird.lspeed = Math.min(bird.lspeed *1.1 || 1, bird.maxSpeed);
} else {
bird.lspeed = Math.max(bird.lspeed - 0.5, 0);
}
if (bird.goingRight) {
bird.rspeed = Math.min(bird.rspeed *1.1 || 1, bird.maxSpeed);
} else {
bird.rspeed = Math.max(bird.rspeed - 0.5, 0);
}
bird.position = bird.position + (bird.rspeed - bird.lspeed);
$("#bird").css('left', bird.position);
requestAnimationFrame(birdLoop);
}());
//Move bird
$(document).keydown(function(e){
switch(e.which){
case 37://left
bird.goingLeft= true;
//left edge of screen
if (bird.position < 0) {
bird.position = 0;
}
break;
case 39://right
bird.goingRight= true;
//right edge of screen
if (bird.position > screenWidth - birdWidth) {
bird.position = screenWidth - birdWidth;
}
default: return;
e.preventDefault();//not sure if needed
}
}).keyup(function(e){
switch(e.which){
case 37://left
bird.goingLeft= false;
//left edge of screen
if (bird.position < 0) {
bird.position = 0;
}
break;
case 39://right
bird.goingRight= false;
//right edge of screen
if (bird.position > screenWidth - birdWidth) {
bird.position = screenWidth - birdWidth;
}
default: return;
e.preventDefault();//not sure if needed
}
});
function spawnPipe()//spawn pipes
{
setInterval(function()
{
astY += 1;
$("#fullPipe").css("top", astY);
}, 10);
}
});
【问题讨论】:
-
碰撞检测是通过获取一个元素的所有四个角的坐标位置来完成的——这很容易用 jQuery 完成——然后你可以比较看看另一个元素的角是否在第一个元素。
-
我刚刚将exact duplicate 合并到这个问题中。请不要继续发布类似这样的重复问题。
标签: jquery css collision-detection flappy-bird-clone