ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript-精灵图像的随机移动位置

2019-10-29 11:36:08  阅读:380  来源: 互联网

标签:sprite-sheet canvas html5-canvas javascript


目前,当我的精灵在画布上移动时,只有在碰到画布的侧面后才会反弹.有没有办法让我的精灵在画布上的随机位置改变到另一个方向?

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

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

另外,您也不想改变每一帧的方向,因此请使用fish.changeDirection();.在动画功能中排成一行.

附带说明一下,您可以考虑让它们独立或随机而不是每次更改x和y方向.这使它看起来更加自然.

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

编辑:JSFiddle

标签:sprite-sheet,canvas,html5-canvas,javascript
来源: https://codeday.me/bug/20191029/1959811.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有