轻松旋转鼠标

Ric*_*hez 3 java processing trigonometry rotation easing-functions

下面的代码使用简单的easy函数将线条旋转到鼠标位置,但问题是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();
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Gob*_*ist 6

不确定我是否正确理解了问题...你的意思是如果鼠标位置略小于+ 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;
Run Code Online (Sandbox Code Playgroud)

如果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;
Run Code Online (Sandbox Code Playgroud)