javascript - Sprite 图像的随机移动位置

标签 javascript canvas html5-canvas sprite-sheet

目前当我的 Sprite 在 Canvas 上移动时,它只会在撞到 Canvas 的一侧后反弹。有没有办法让我的 Sprite 在 Canvas 上的随机位置改变到另一个方向?

这是我改变方向及其移动方式的代码:

Fish.prototype.changeDirection = function () {
    speedXSign = this.speedX > 0 ? 1 : -1;
    speedYSign = this.speedY > 0 ? 1 : -1;
    this.speedX = speedXSign * (1 + Math.random() * 2);
    this.speedY = speedYSign * (1 + Math.random() * 2);
};

Fish.prototype.move = function () {
    this.animIndex++;
    if ( this.animIndex == animFrames.length) this.animIndex = 0;

    this.xPos += this.speedX;
    if ((this.xPos + this.frameWidth * this.frameScale / 2) >= canvas.width && this.speedX > 0 || 
        (this.xPos - this.frameWidth * this.frameScale / 2) <= 0 && this.speedX <= 0) {
        this.speedX = -this.speedX;
    }

    this.yPos += this.speedY;
    if ((this.yPos + this.frameHeight * this.frameScale / 2) >= canvas.height && this.speedY > 0 || 
        (this.yPos - this.frameHeight * this.frameScale / 2) <= 0 && this.speedY <= 0) {
        this.speedY = -this.speedY;
    }
};

最佳答案

一个相当简单的选择是随机选择一段时间,然后让鱼在这段时间后改变方向。我的第一个想法是使用 setTimeout。我注意到您的 changeDirection 函数中的比较是向后的,所以我修复了它并将其设置为在随机时间后调用自身。

Fish.prototype.changeDirection = function () {
    var me = this;
    var speedXSign = this.speedX < 0 ? 1 : -1;
    var speedYSign = this.speedY < 0 ? 1 : -1;
    this.speedX = speedXSign * (1 + Math.random() * 2);
    this.speedY = speedYSign * (1 + Math.random() * 2);
    var time = 1000 + 2000*Math.random();
    setTimeout(function() {me.changeDirection()}, time);
};

您可以通过调整时间变量来改变他们转身的频率。 然后,当您添加一条新鱼时,您需要初始化 changeDirection 循环,因此 init 可能如下所示:

function init() {
    frameWidth = imgFish.width / frameCount ; 
    frameHeight = imgFish.height ; 

    document.getElementById("button").onclick = function() {
        // create another fish using the Fish class
        var anotherFish = new Fish(xPos, yPos, speedX, speedY, imgFish, frameWidth, frameHeight);
        // put this new fish into the fishes[] array
        fishes.push(anotherFish) ;
        // make it start changing directions
        anotherFish.changeDirection();
        // draw this new fish
        anotherFish.drawFish();
    }
    animate();
}

此外,您不希望每一帧都改变方向,因此请从 animate 函数中取出 fish.changeDirection(); 行。

作为旁注,您可以考虑让它们独立地或随机地而不是每次都改变 x 和 y 方向。这使它看起来更自然。

    var speedXSign = Math.random() < 0.5 ? 1 : -1;
    var speedYSign = Math.random() < 0.5 ? 1 : -1;

编辑:JSFiddle

关于javascript - Sprite 图像的随机移动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24378155/

相关文章:

javascript - 在 IE9 上对新 Canvas 的第一次绘制图像调用很慢

javascript - Canvas 矩形背景图像

javascript - 读取 Canvas 像素的 RGB 值

javascript - 如何知道所需文件的确切路径()

javascript - 现代浏览器中 HTML 4 网站上的 LocalStorage?

javascript - ckeditor4,除非需要,否则删除垂直滚动

javascript - 优化js - 保存对象中复选框的值

javascript - 如何防止默认右键单击包含图像的 Canvas

javascript - 挑战: Fix a Canvas plugin to work with CORS?

javascript - HTML5 Context/Canvas - 何时在上下文上调用绘制