有人可以解释我如何在蛇头附近产生新尾部,因为新部件出现在0/0上
var makeAStep = function() {
if (snake.detectCollision(snake.velocity) === true) {
alert("You Loose, what a pity!");
clearInterval(intervalHandler);
return;
}
var lastItemPosition = snake.body[snake.body.length - 1].position.copy();
snake.move();
if (snake.getHead().isOnPosition(food.position)) {
food.updateScore();
generateFood();
snake.body.push(new snakeItem(lastItemPosition));
}
snake.screenUpdate();
我认为我必须在这里编辑一些内容:
screenUpdate: function() {
var offset = 0;
var currentNode = null;
for (i in this.body) {
offset = 3 + parseInt(i);
currentNode = $('#box :nth-child(' + offset + ')');
if (currentNode.size() == 0)
$('#box').append($('<div class="snakeItem"></div>'));
currentNode.animate({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
currentNode.animate({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
}
答案 0 :(得分:3)
您的问题是您在.animate()
中使用的snake.screenUpdate()
功能。例如,如果您将其更改为.css()
,则会直接看到新项目。当然,这会破坏蛇的其余部分的平稳运动,所以你可能想要区别对待物品,例如:
for (i in this.body) {
offset = 3 + parseInt(i);
currentNode = $('#box :nth-child(' + offset + ')');
if (currentNode.size() == 0) {
$('#box').append($('<div class="snakeItem"></div>'));
currentNode = $('#box :nth-child(' + offset + ')');
currentNode.css({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
currentNode.css({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
} else {
currentNode.animate({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
currentNode.animate({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
}
}
如果我理解你的小提琴,这应该有用。
答案 1 :(得分:1)
$('#box').append($('<div class="snakeItem"></div>'));
Replace above code with following code.
var element = $('#box').find(".snakeItem").last();
var elementtop= $(testelement).css( "top");
var elementleft= $(testelement).css( "left");
$("<div>", {
'class': "snakeItem",
css: {
"top": elementtop,
"left":elementleft
}
}).appendTo($('#box'));