0
目前我正在制作鱼类动画。我的鱼精灵是动画并能够在画布上自由移动。其次,我想添加食物以在画布上喂食鱼类。但是现在我被卡住了,无法让鱼在画布上画画时游向食物。将精灵图像移动到选定位置
下面是我的鱼精灵是随机移动:
Fish.prototype.changeDirection = function() {
var me = this;
var speedXSign = Math.random() < 0.5 ? 1 : -1;
var speedYSign = Math.random() < 0.5 ? 1 : -1;
this.speedX = speedXSign * (1 + Math.random() * 1.6);
this.speedY = speedYSign * (1 + Math.random() * 1.6);
var time = 1000 + 2000*Math.random();
setTimeout(function() {me.changeDirection()}, time);
};
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/1.8) >= canvas.width && this.speedX > 0 ||
(this.xPos - this.frameWidth * this.frameScale/1.8) <= 0 && this.speedX <= 0) {
this.speedX = -this.speedX;
}
this.yPos += this.speedY;
if ((this.yPos + this.frameHeight * this.frameScale/1.8) >= canvas.height && this.speedY > 0 ||
(this.yPos - this.frameHeight * this.frameScale/1.8) <= 0 && this.speedY <= 0) {
this.speedY = -this.speedY;
}
};
,现在当我的onclick在画布上,将食物与X和Y偏移量出现一起。
function addFood(foodArray){
var iiimage = new Image();
iiimage.src = 'Images/redFood.png';
for(var m = 0 ; m<foodArray.length;m++){
var x = foodArray[m].x;
var y = foodArray[m].y;
context.drawImage(iiimage,x,y,50,50);
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.onmousedown = function(e){
foodX = getMousePos(canvas,e).x;
foodY = getMousePos(canvas,e).y;
food = {x:foodX,y:foodY};
foodArray.push(food);
console.log('('+foodX+','+foodY+')');
console.log(food);
console.log(foodArray.length);
}
是否有可能使鱼精灵改变它的方向最近的食物可用,然后返回到它的鱼精灵已与食品接触后随机运动。
这里是我的小提琴:http://jsfiddle.net/Bernard_9/bV4r6/
是的,它适用于我在Windows和Ubuntu上使用Chrome。 –
我可以问你另一个问题吗?这是否可以在画布上放置一个按钮来启用/禁用馈送?@JaredNeil – TypeB
从来没有自己做过,但[这个问题](http://stackoverflow.com/questions/4797748/can-i-put-an-html-button-inside-the-canvas)似乎可能会回答你的问题题。 –