This forum is read only and just serves as an archive. If you have any questions, please post them on

1 decade ago by Jesse

How do I convert an angle, like the result of Entity's angleTo function into a trajectory expressed as an x and y delta values. So an angle becomes a path that I can shoot an entity using. I'll call angleTo and then shoot stuff using x and y values that won't change, just need the x and y from the angle.

180 returns { x: -1, y: 0 }

45 returns { x: 1, y: -1 }

I know math can save me here, I just can't find anything with Google to solve this!

1 decade ago by Alex

This will explain the theory -

1 decade ago by MikeL

I've got a function, but not at my computer. Will try to post it later.

1 decade ago by paularmstrong

This should do the trick:

var angle = this.angleTo(target);
var x = Math.cos(angle);
var y = Math.sin(angle);

1 decade ago by MikeL

Here is a slightly more complicated example for a rotating cannon (probably different than what you are doing, but may be helpful to others).
  calculateAngle: function() {
              sinAngle = Math.sin(this.anims.idle.angle);
              cosAngle = Math.cos(this.anims.idle.angle);
              bulletX = (this.pos.x + this.halfWidth) + (47 * sinAngle);
              bulletY = (this.pos.y + 47) - (47 * cosAngle);
              return {x: bulletX, y: bulletY, sin: sinAngle, cos: cosAngle};

This is from a game I am working on where the player's cannon fires bullets, etc. The trajectory of the bullet depends in this case on the direction of the cannon. The cannon can be rotated to different angles. The cannon is simple elongated vertical box oriented upwards initially. The actual position of the bullet relative to the cannon also has to be calculated as seen above.

The bullet is actually spawned here:
                trajectory = this.calculateAngle();
       EntityPlayerFire, trajectory.x, trajectory.y, { vel:{x: trajectory.sin, y: -trajectory.cos} } );

As you can see the x velocity is actually associated with sin and the y velocity is the negative of the cos. This takes into account the initial orientation of the cannon (angle 0) which actually points straight upwards.

1 decade ago by Jesse

Looks like the answer is to use sin and cos. Thanks everyone.

1 decade ago by PhillipSchmidt

Page 1 of 1
« first « previous next › last »