2011-04-18 169 views
3

下面的代码使用简单的缓动功能将线条朝鼠标位置旋转,但问题在于atan2()方法的工作形式-PI到PI,使得线条向后旋转达到任何一个限制,我可以使它从0旋转到TWO_PI,但没有什么不同,因为线会向后旋转直到它到达targetAngle,如果我不使用宽松计算可以正常工作,因为从-PI跳转到了PI是不明显的,那么我怎样才能缓解我的旋转并避免这个问题呢?轻松旋转朝向鼠标

float angle = 0; 
float targetAngle = 0; 
float easing = 0.1; 

void setup() { 
    size(320, 240); 
} 

void draw() { 
    background(200); 
    noFill(); 
    stroke(0); 

    // get the angle from the center to the mouse position 
    angle = atan2(mouseY - height/2, mouseX - width/2); 
    // check and adjust angle to go from 0 to TWO_PI 
    if (angle < 0) angle = TWO_PI + angle; 

    // ease rotation 
    targetAngle += (angle - targetAngle) * easing; 

    pushMatrix(); 
    translate(width/2, height/2); 
    rotate(targetAngle); 
    line(0, 0, 60, 0); 
    popMatrix(); 
} 

感谢

回答

5

不知道如果我理解正确的问题......你的意思是,如果鼠标位置比+ PI略显不足,而且targetAngle比-PI稍大,然后行旋转离开鼠标?即使两个值都在相同的范围内(-PI,PI),它们仍然可能相距很远。您必须调整angle以适合当前targetAngle值的PI邻域。

// get the angle from the center to the mouse position 
angle = atan2(mouseY - height/2, mouseX - width/2); 
// check and adjust angle to be closer to targetAngle 
if (angle < targetAngle - PI) angle = angle + TWO_PI; 
if (angle > targetAngle + PI) angle = angle - TWO_PI; 

如果targetAngle是在(-TWO_PI,TWO_PI)的范围这将工作。看来它会为你工作。如果targetAngle可以有任何非常远离工作范围的值,那么你可以使用类似这样的东西:

// get the angle from the center to the mouse position 
angle = atan2(mouseY - height/2, mouseX - width/2); 
// calculate the shortest rotation direction 
float dir = (angle - targetAngle)/TWO_PI; 
dir = dir - Math.round(dir); 
dir = dir * TWO_PI; 

// ease rotation 
targetAngle += dir * easing;