java—设置处理向量的恒定速度

kse8i1jr  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(519)

我在处理过程中有一个向量跟踪鼠标点击:

  1. friendlies.get(i).setXSpeed((friendlies.get(i).getmx()-friendlies.get(i).getX())/100);
  2. friendlies.get(i).setYSpeed((friendlies.get(i).getmy()-friendlies.get(i).getY())/100);
  3. ``` `friendlies.get(i` )是向量和 `getmx()` 返回鼠标单击时的位置。唯一的问题是速度会随着矢量接近目的地而降低,我不知道如何使速度恒定。
flvlnr44

flvlnr441#

尝试以下操作:
1) 获取方向向量(从元素到鼠标点击)
2) 将此方向向量规格化为单位向量
3) 使用这个单位向量作为速度(你可以用它乘以一些常数因子)

  1. PVector pos = friendlies.get(i);
  2. // direction vector
  3. PVector dir = new PVector(mouseX - pos.x, mouseY - pos.y);
  4. // now it becomes unit-vector (with length 1)
  5. dir.normalize();
  6. pos.x = pos.x + dir.x * factor;
  7. pos.y = pos.y + dir.y * factor;

相关问题