精灵图像的随机移动位置
Random moving position for sprite image
目前,当我的精灵在画布上移动时,它只会在击中画布的一侧后反弹。是否有办法让我的精灵在画布上的随机位置改变到另一个方向?
这是我的代码改变方向和它如何移动:
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();
线从animate
函数中去掉。
作为旁注,您可以考虑让它们独立或随机地改变x和y方向,而不是每次都改变。这使它看起来更自然。
var speedXSign = Math.random() < 0.5 ? 1 : -1;
var speedYSign = Math.random() < 0.5 ? 1 : -1;
编辑:JSFiddle
相关文章:
- 在不移动元件的情况下从相对位置更改为固定位置
- 如何在鼠标悬停时将对象从起始位置移动到结束位置,然后在鼠标悬停后再次移动
- 将插入符号位置移动到ContentEditable<DIV>
- 我发现了一些只在移动设备上可见的垃圾邮件链接,我可以'找不到包含此垃圾邮件链接的脚本的位置
- float's未返回到移动视图结束后的位置
- 将javascript数组中的项移动到特定位置的有效方法
- 如何将节点移动到所需位置
- Photoshop脚本:将图像移动到位置x,y
- 在鼠标上触发鼠标移动'的当前位置
- 固定图像滚动移动位置
- Javascript滚动和移动位置
- 如何确保按钮点击均匀移动位置
- 当地图移动时,必应地图InfoBox会在FireFox和Chrome中移动位置
- 当尝试按下鼠标选择所有对象时,对象会自动移动位置(Fabric.JS)
- 在必应地图上获取移动位置
- 精灵图像的随机移动位置
- 如何将多个标记添加到移动位置谷歌地图,Javascript
- 创建用于移动位置的常量而不是变量
- 如何根据鼠标移动/位置应用效果
- MediaWiki我如何得到[折叠]链接不移动位置与文本