简体   繁体   English

如何以最短的方式将角度变量移向目标角度

[英]How to move an angle variable towards a target angle in the shortest way

My game units have an angle variable, and a targetAngle variable. 我的游戏单元有一个angle变量和一个targetAngle变量。 These variables range from 1 to 360 degrees. 这些变量的范围是1到360度。

The angle variable should always move towards the targetAngle variable. 角度变量应始终移向targetAngle变量。

The problem is, it doesn't happen in the shortest way. 问题是,它不会以最短的方式发生。 When the targetAngle is 350 degrees, and the current angle is only 10 degrees, the variable should only move by 20 degrees instead of incrementing by 340 degrees, as I have now. 当targetAngle为350度且当前角度仅为10度时,变量应仅移动20度,而不是像我现在那样增加340度。

How can I make the angle variable move towards the targetAngle variable in the shortest way? 如何使角度变量以最短的方式向targetAngle变量移动?

Live demo: http://jsfiddle.net/zNsbc/ 现场演示: http//jsfiddle.net/zNsbc/

var angle = 10;
var targetAngle = 350;

setInterval(function() {

    if ( angle > targetAngle ) {
        angle--;
    }
    else if ( angle < targetAngle ) {
        angle++;
    }    

    $("#angle").text(angle);

}, 10);

You should realize that 360 is the same as 0, so you can compare angle with targetAngle and also with targetAngle+360 and move it to the direction to which it is closest (consider -360 as well for angles close to 0 and targetAngle close to 360) 您应该意识到360与0相同,因此您可以将角度与targetAngle以及targetAngle + 360进行比较,并将其移至最接近的方向(对于接近0的角度和targetAngle的接近角度,也请考虑-360 360)

So your example: 所以你的例子:

angle:            10
targetAngle:      350 (diff 340)
targetAngle+360:  710 (diff 700)
targetAngle-360: - 10 (diff  20)

angle is closest to targetAngle-360, so you would decrement it, instead of incrementing it 角度最接近targetAngle-360,因此您可以减少它,而不是增加它

Note : make sure to take absolute value for the difference 注意 :确保取绝对值作为差值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM