java - 轻松向鼠标旋转

标签 java rotation processing trigonometry easing-functions

下面的代码使用简单的缓动函数将线向鼠标位置旋转,但问题是 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();
}

谢谢

最佳答案

不确定我是否理解正确......你的意思是如果鼠标位置略小于+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;

关于java - 轻松向鼠标旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5701006/

相关文章:

ios - 横向和纵向的独立 xibs

java - 在处理中更改聚光灯方向

java - 处理 3 - 使用 noFill() 后填充形状

java - IntelliJ 在整个文件中应用检查修复

jquery - 旋转图像、div 或列表元素的最佳方式

javascript - 你如何在angularjs中旋转图像

java - 在eclipse中使用minim。音乐文件放在哪里?

java - 拆分二叉搜索树

java - 使用新的与正常的减速和整数的性质来声明变量(装箱/拆箱)

java - 为 Android 设置解析推送通知