我知道这不是最好的问题,但我真的卡住了。我尝试在此链接中创建类似on的游戏:http://richard.parnaby-king.co.uk/examples/games/balloons/,仅使用Jquery / Javascript / CSS / HTML。 (所以我不能使用闪光灯。)
我知道游戏看起来不太好或不流利,但我现在所做的甚至不能工作。
首先,我创造了一个div,它将成为“游戏领域”。然后我想每隔200毫秒在页面底部添加一个气球,该气球会上升。它适用于一个气球,但是当我添加更多气球时,气球会在.animate功能开始时跳到屏幕顶部。
var divheight = $("#playfield").height();
var divwidth = $("#playfield").width();
var y = 0;
while (y<=20) {
var position = Math.round(divwidth*Math.random());
setTimeout(function(){
var testballoon = '<img src="Afbeeldingen/testballon.png" class="blueballoon"'
testballoon+= 'style="position:absolute;bottom:0px;' + 'left:' + position + 'px;"/>';
$("#playfield").append(testballoon);
}, 1000); y++}
但是我甚至无法将图像放在一个好位置,并且让它们动起来就像我打算那样工作。我并没有要求使用现成的代码,但如果有人对这样的事情有任何经验并且知道更好的方法来随机添加元素/在页面上移动它们,我会很感激。< / p>
答案 0 :(得分:0)
Here is a JSFiddle example一种创建新对象的方法,为它们设置动画,然后将其删除。以下是此示例的代码。除非你喜欢看气球漂浮,否则要想成为一款游戏还有很长的路要走!
HTML
<div class="gamefield">
Click this area to add balloons!
<br />
Click fast or click slow!
</div>
CSS
div.gamefield {
width: 100%;
height: 500px;
border: 1px red solid;
}
div.balloon {
position: absolute;
bottom: 0px;
left: 0px;
width: 100px;
height: 150px;
background-size: 100% 100%;
background-repeat: no-repeat;
}
的Javascript
var burl = "http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons/green-jelly-icons-culture/028931-green-jelly-icon-culture-balloon.png";
function createBalloon() {
var gamefield = $("div.gamefield");
var d = $(document.createElement("div"));
d.addClass("balloon");
d.css("background-image", "url('" + burl + "')");
var maxwidth = gamefield.width() - 100;
var left = Math.round(maxwidth * Math.random());
d.css("left", left+"px");
d.css("bottom", "0px");
gamefield.append(d);
d.animate({
bottom: gamefield.height()
}, 3000, function() {
animationComplete($(this));
});
}
function animationComplete(jobj) {
jobj.remove();
}
$(function() {
$("div.gamefield").click(function() {
createBalloon();
});
});
答案 1 :(得分:0)
检查此 FIDDLE
的jQuery
var div ="<div class='balloon'></div>";
var $div = $(div);
var totalHits = 0;
var totalSeconds = 30;
var time = 0;
var colors = ["red","green","blue","yellow","brown","orange","black","gray"];
var game = setInterval(function(){
time = time + 3;
for(i=0;i<5;i++){
var numBottom = Math.floor(Math.random()*100);
var numLeft = Math.floor(Math.random()*300);
var colorRand = colors[Math.floor(Math.random()*colors.length)];
var cloneDiv = $div.clone(true);
cloneDiv.css({
"background-color":colorRand,
"bottom":-numBottom,
"left":numLeft
}).appendTo("#panel");
cloneDiv.animate({
bottom:"700px"
},20000,function(){
cloneDiv.remove();
});
cloneDiv.on("click",function(){
$(this).hide();
totalHits = totalHits + 1;
});
if(time > totalSeconds){
clearInterval(game);
$("#panel").html("<h2>Game Over</h2><br/><h3>your Score: " + totalHits + "</h3>");
}
}
},3000);