javascript - 蛇游戏尾部的正确位置

标签 javascript jquery html

有人可以解释我该怎么做才能在蛇头附近生成新的尾部部分,因为新部分出现在 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();

fiddle with all the code.

我想我必须在这里编辑一些东西:

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);
    }

最佳答案

您的问题是您在 snake.screenUpdate() 中使用的 .animate() 函数。例如,如果将它们更改为 .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);
    }
}

如果我正确理解你的 fiddle ,这应该有效。

关于javascript - 蛇游戏尾部的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22958936/

相关文章:

javascript - jQuery:用逗号分隔值?

javascript - 使用 jquerymobile 1.4 删除按钮并将属性添加到按钮

javascript - 向可观察的响应添加附加参数

javascript - HTML 中的透明彩色前景?

javascript - 如何使用 CasperJS 打开多个 URL 并将多个链接捕获为图像

jquery - 将事件添加到 id 以 “user” 开头的所有链接?

javascript - 为什么这个 JavaScript 广告只有在 &lt;iframe&gt; 中加载时才会被裁剪?

html - 在容器调整大小中输入文本大小

html - 单引号和双引号 (' vs ")

javascript - 在 Python 中使用 Selenium 提交表单