user6842975
user6842975

Reputation: 11

JavaScript canvas make object shoot toward object

I'm new in JavaScript and I'm creating a kind of shooting game. I'm to make 1 object to move toward another object. So the "bullet" get the location of the "prey" and it will move toward it. I have no idea how to implement that, I can't find anything similar on the internet. So, I tried at first something simpler:

In the following code the "bullet" move to the left. How can I specify to move it toward an object? I have 2 object. It's the enemyBullet object(not the bullet object) which should go toward another object. PS: English is not my native language. Sorry for any confusion thanks.

     this.draw = function () {
            this.context.clearRect(this.x + 2, this.y + 1.5, this.width - 4.5, this.height);
//x+ the speed make it go to the left
            this.x += this.speed;
            if (self === "bullet" && this.x >= this.canvasWidth) {
                return true;
            }
            else if (self === "enemyBullet" && this.x >= 1000) {
                console.log(this.x);
                return true;
            }
            else {
                if (self === "bullet") {
                    this.context.drawImage(imageRepository.bullet, this.x, this.y);
                }
                else if (self === "enemyBullet") {
                    this.context.drawImage(imageRepository.enemyBullet, this.x, this.y);
                }
                return false;
            }
        };

Upvotes: 0

Views: 669

Answers (1)

Blindman67
Blindman67

Reputation: 54089

Normalised vector

You need to find the normalised vector from one object to the next. A vector is just an arrow that has a direction and a length. In this case we normalise the length, that is make it equal to 1 unit long. We do this so we can easily set a speed when using the vector.

Function to return a vector from one point to the next

// Code is in ES6
// fx, fy is from coordinate
// tx, ty is to coordinate
function getNormVec(fx, fy, tx, ty){
    var x = tx - fx;  // get differance
    var y = ty - fy;
    var dist = Math.sqrt(x * x + y * y); // get the distance.
    x /= dist;  // normalised difference
    y /= dist;
    return {x,y};
} 

Once you have the vector you can move an object by adding the vector times the speed. Example of creating and moving a bullet from myObj to myTarget

var myObj = {}
var myTarget = {};
var myBullet = {}
myObj.x = 100;
myObj.y = 100;
myTarget.x = 1000
myTarget.y = 1000

var vecToTag = getNormVect(myObj.x, myObj.y, myTarget.x, myTarget.y);
myBullet.nx = vecToTag.x; // set bullets direction vector
myBullet.ny = vecToTag.y;
myBullet.x = myObj.x; // set the bullet start position.
myBullet.y = myObj.y;
myBullet.speed = 5; // set speed 5 pixels per frame

To move the bullet

myBullet.x += myBullet.nx * myBullet.speed;
myBullet.y += myBullet.ny * myBullet.speed;

Upvotes: 1

Related Questions