Currently I'm working on a fish animation. My fish sprite is animated and able to move freely on the canvas. Secondly I wanted to add food to feed the fishes on the canvas. But currently I'm stuck and couldn't get the fishes to swim towards the food when it's draw on the canvas.
Here is how my fish sprite is moving randomly:
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;
}
};
And now when I Onclick on the canvas, the food will appear and together with the X and Y Offsets.
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);
}
Is it possible to make the fish sprite change it's direction to the nearest food available and then back to it's random movement after the fish sprite has made contact with the food.
Here is my fiddle: http://jsfiddle.net/Bernard_9/bV4r6/