TypeB
TypeB

Reputation: 97

Sprite movement style towards one specific point

My sprite image will be moving randomly on the canvas. But after i press on the canvas an object will appear and the sprite image will be moving in a zig zag manner towards it. But i want the sprite to move directly towards the object.

How my sprite image move towards the image that i created after pressing on the canvas:

Fish.prototype.chaseFood = function(index) {
    if (this.xPos > foodArray[index].x + foodWidth) {
        this.speedX = -1 * Math.abs(this.speedX);
    } else if (this.xPos < foodArray[index].x) {
        this.speedX = Math.abs(this.speedX);
    }
    if (this.yPos > foodArray[index].y + foodHeight) {
        this.speedY = -1 * Math.abs(this.speedY);
    } else if (this.yPos < foodArray[index].y) {
        this.speedY = Math.abs(this.speedY);
    }
};

I know there is a way that is by calculating the slope of the line between the point of the sprite and the object so to allow my sprite image to move towards. But after trying i still couldn't get it. Anybody knows how to achieve it?

Upvotes: 1

Views: 133

Answers (1)

Loktar
Loktar

Reputation: 35309

You canchange your code to the following for chaseFood

Fish.prototype.chaseFood = function (index) {    
    var tx = foodArray[index].x + foodWidth - this.xPos,
        ty = foodArray[index].y + foodHeight - this.yPos,
        dist = Math.sqrt(tx*tx+ty*ty); // better ways to do the distance.

        // 1 can be any speed value to make it go faster or slower
        this.speedX = (tx/dist)*1;
        this.speedY = (ty/dist)*1;
};

What this does is gets the distance between the fish and the food, and divides the current x, and y component by the distance making it travel towards the food at a constant speed. Yours was always 1 or -1 so it would bounce back and forth, this method allows it to be a float so it can travel exactly towards the food.

I adapted the code from an article on my blog which has other helpful recipes for this sort of thing.

Live Demo

Upvotes: 1

Related Questions