Skip to content

Commit 688752c

Browse files
committed
Math.getShortestAngle will return the shortest angle between the two given angles. Angles are in the range -180 to 180, which is what Sprite.angle uses. So you can happily feed this method two sprite angles, and get the shortest angle back between them (phaserjs#2494)
1 parent 3c3d09e commit 688752c

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ You can read all about the philosophy behind Lazer [here](http://phaser.io/news/
315315
* Group.iterate has a new `returnType`: `RETURN_ALL`. This allows you to return all children that pass the iteration test in an array.
316316
* The property `checkCollision.none` in the ArcadePhysics.Body class was available, but never used internally. It is now used and checked by the `separate` method. By setting `checkCollision.none = true` you can disable all collision and overlap checks on a Body, but still retain its motion updates (thanks @samme #2661)
317317
* Math.rotateToAngle takes two angles (in radians), and an interpolation value, and returns a new angle, based on the shortest rotational distance between the two.
318+
* Math.getShortestAngle will return the shortest angle between the two given angles. Angles are in the range -180 to 180, which is what `Sprite.angle` uses. So you can happily feed this method two sprite angles, and get the shortest angle back between them (#2494)
318319

319320
### Updates
320321

src/math/Math.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,30 @@ Phaser.Math = {
371371

372372
},
373373

374+
/**
375+
* Gets the shortest angle between `angle1` and `angle2`.
376+
* Both angles must be in the range -180 to 180, which is the same clamped
377+
* range that `sprite.angle` uses, so you can pass in two sprite angles to
378+
* this method, and get the shortest angle back between the two of them.
379+
*
380+
* The angle returned will be in the same range. If the returned angle is
381+
* less than 0 then it's a counter-clockwise rotation, if >= 0 then it's
382+
* a clockwise rotation.
383+
*
384+
* @method Phaser.Math#getShortestAngle
385+
* @param {number} angle1 - The first angle. In the range -180 to 180.
386+
* @param {number} angle2 - The second angle. In the range -180 to 180.
387+
* @return {number} The shortest angle, in degrees. If less than zero it's counter-clockwise, otherwise clockwise.
388+
*/
389+
getShortestAngle: function (angle1, angle2) {
390+
391+
var difference = angle2 - angle1;
392+
var times = Math.floor((difference - (-180)) / 360);
393+
394+
return (difference - (times * 360)) * -1;
395+
396+
},
397+
374398
/**
375399
* Find the angle of a segment from (x1, y1) -> (x2, y2).
376400
*

0 commit comments

Comments
 (0)