tower defense bullet following enemy with range javascript

Solutions on MaxInterview for tower defense bullet following enemy with range javascript by the best coders in the world

showing results for - "tower defense bullet following enemy with range javascript"
Will
07 Oct 2016
1//Please note, that this is not my script, it was made by a guy from StackOverflow named "gnarf"
2//Thanks
3
4// this is a "constant"  - representing 10px motion per "time unit"
5var bulletSpeed = 10; 
6// calculate the vector from our center to their center
7var enemyVec = vec_sub(targetSprite.getCenter(), originSprite.getCenter());
8// measure the "distance" the bullet will travel
9var dist = vec_mag(enemyVec);
10// adjust for target position based on the amount of "time units" to travel "dist"
11// and the targets speed vector
12enemyVec = vec_add(enemyVec, vec_mul(targetSprite.getSpeed(), dist/bulletSpeed));
13// calculate trajectory of bullet
14var bulletTrajectory = vec_mul(vec_normal(enemyVec), bulletSpeed);
15// assign values
16bulletSprite.speedX = bulletTrajectory.x;  
17bulletSprite.speedY = bulletTrajectory.y;  
18
19// functions used in the above example:
20
21// getCenter and getSpeed return "vectors"
22sprite.prototype.getCenter = function() { 
23  return {
24    x: this.x+(this.width/2), 
25    y: this.y+(this.height/2) 
26  }; 
27};
28
29sprite.prototype.getSpeed = function() { 
30  return {
31    x: this.speedX, 
32    y: this.speedY 
33  }; 
34};
35
36function vec_mag(vec) { // get the magnitude of the vector
37  return Math.sqrt( vec.x * vec.x + vec.y * vec.y); 
38 }
39function vec_sub(a,b) { // subtract two vectors
40  return { x: a.x-b.x, y: a.y-b.y };
41}
42function vec_add(a,b) { // add two vectors
43  return { x: a.x + b.x, y: a.y + b.y };
44}
45function vec_mul(a,c) { // multiply a vector by a scalar
46  return { x: a.x * c, y: a.y * c };
47}
48function vec_div(a,c) { // divide == multiply by 1/c
49  return vec_mul(a, 1.0/c);
50}
51function vec_normal(a) { // normalize vector
52  return vec_div(a, vec_mag(a)); 
53}
54
similar questions