0
\$\begingroup\$

I'm trying to make a tank character for my game but I couldn't do the math of firing bullets from turret instead of center of the tank.

I tried some Stack Overflow solutions but I couldn't understand them correctly or they weren't related to my issue.

this.angle = (rotation in radians) + Math.PI / 2
var x = -40 * Math.sin(this.angle) - -40 * Math.cos(this.angle);
var y = -40 * Math.cos(this.angle) + -40 * Math.sin(this.angle);

turretX = turretX - x;
turretY = turretY - y;

Now, as you can imagine, the position is always 40px wrong. That's expected since I try to change values of both x and y regardless of whether they're already correct or not.

How can I get the correct x, y?

\$\endgroup\$
0
\$\begingroup\$

If you know the angle and position of the turret, then it's simply

x = turretPosX + cos(angle) * barrelLength
y = turretPosY + sin(angle) * barrelLength
\$\endgroup\$
0
\$\begingroup\$

I found an answer in a random stackoverflow post, not sure if there's better ways to do this but it works. Feel free to post your way if you think that's better.

var turretX =
  (0 - 0) * Math.cos(rotation) - (40 - 0) * Math.sin(rotation) + 0;
var turretY =
  (40 - 0) * Math.cos(rotation) + (0 - 0) * Math.sin(rotation) + 0;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.