我在做某種jQuery
遊戲並卡住了。我需要幫助兩件事。jquery,timeinterval和if語句
我有一個玩家玩板。玩家正在鍵盤上的箭頭幫助下移動。我的問題是玩家不在遊戲板之外,我不想要這個。我該怎麼做才能使它無法在盒子外面出現。
我做了某種「食物」,每次刷新時隨機產生一個X位置。但是我希望它每隔一秒產生一個隨機位置,因此在板上可以有多個「食物」。
以下是我有:
$(document).ready(function() {
$(document).keydown(function(e) {
if (e.keyCode ==39 && $("#spelare").css("left") < '880px')
$("#spelare").animate({left: '+=20px'}, 0);
else if (e.keyCode ==37 && $("#spelare").css("left") > '0px')
$("#spelare").animate({left: '-=20px'}, 0);
});
$('.food').each(function() {
var spelplanWidth = $('#spelplan').width();//Screen width
var foodPosX = Math.floor((Math.random() * spelplanWidth));
$(this).css('left', foodPosX);
setInterval(function() {
var spelplanWidth = $('#spelplan').width();//Screen width
var foodPosX = Math.floor((Math.random()*spelplanWidth));
$(this).css('left', foodPosX);
}, 1000);
});
});
body {
text-align: center;
background-color:black;
}
#spelplan{
width: 50%;
height:65vh;
position:absolute;
margin-left:25%;
box-shadow: inset 0px 0px 50px;
background-color: green;
}
#spelare{
width:15%;
height: 12vh;
position: relative;
top:53.4vh;
background-color:red;
}
.food{
width:5%;
height:5vh;
position:relative;
background-color:blue;
}
p {
position:relative;
font-family: 'Electrolize', sans-serif;
}
#poäng{
color:white;
bottom:17vh;
right:45%;
}
#liv{
color:white;
bottom:18vh;
right:46.5%;
}
.fa-heart{
color:red;
bottom:21.5vh;
right:43.5%;
position:relative;
}
#info{
color:white;
font-family: 'Electrolize', sans-serif;
margin-top:68vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 style="color:white">JQUERY SPEL</h2>
<div id="spelplan">
<div id="spelare"> </div>
<div class="food"> </div>
<p id="poäng"> Poäng: </p>
<p id="liv"> Liv: </p>
<i class="fa fa-heart" aria-hidden="true"></i>
</div>
哎呀,你必須在你的代碼格式上工作,看看我已經做了編輯,看看你的代碼應該如何格式化。 – Zac
我會避免在CSS選擇器中使用特殊字符,例如:'#poäng'。 – Zac