night - 1 year ago 73

Javascript Question

All my searching comes up with more general arc/sin/cos usage or shooting to the mouse position.

I am looking to aim and fire a projectile with the keyboard and have done a lot of it from scratch, as a noob in a web class doing a project, but I am stuck on this. My current math got me to this mess in firing the shot in the direction the line is currently pointing... (code names cleaned for readability):

`this.x = x + len * Math.cos(angle);`

this.y = y + len * Math.sin(angle);

this.xmov = -((x + len * Math.cos(angle)) - x) / ((y + len * Math.sin(angle)) - y);

this.ymov = ((y + len * Math.sin(angle)) - y) / ((x + len * Math.cos(angle)) - x);

if (Math.abs(this.xmov) > Math.abs(this.ymov)) {

this.xmove = (this.xmov * Math.abs(this.ymov));

} else {

this.xmove = this.xmov;

}

if (Math.abs(this.ymov) > Math.abs(this.xmov)) {

this.ymove = (this.xmov * this.ymov);

} else {

this.ymove = this.ymov;

}

(And here is the full thing http://jsbin.com/ximatoq/edit. A and D to turn, S to fire (on release). Can also hold S while turning.)

... but, you'll see that it only works for 3/8's of it. What is the math to make this fire from a complete circle?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Use this as shoot function:

```
this.shoot = function() {
if (this.fire > 0) {
this.x = P1gun.x2;
this.y = P1gun.y2;
this.xmove = (P1gun.x2 - P1gun.x)/100;
this.ymove = (P1gun.y2 - P1gun.y)/100;
this.fire = 0;
this.firetravel = 1;
}
}
```

The `/100`

can be removed, but you have to reduce the projectile speed.

If you want to shoot gun2 change the P1gun to P2gun.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**