【问题标题】:Calculating bullet speed计算子弹速度
【发布时间】:2014-09-11 15:44:34
【问题描述】:

我需要计算子弹的 X 和 Y 速度(子弹将通过这些移动每个“更新”),所以我有关注

public int[] getXandYSpeed(int pointOfOriginX, int pointOfOriginY, int aimToX, int aimToY){
  int[] coords = new int[2];
  aimToX = aimToX - pointOfOriginX;
  aimToY = aimToY - pointOfOriginY;

  while((aimToX + aimToY) > 5){
    aimToX = aimToX/2;
    aimToY = aimToY/2;
  }

  coords[0] = aimToX;
  coords[1] = aimToY;
  return coords;

但是,这并不是很准确,并且子弹具有随机速度(如果最终循环中的 final 是 aimToX 加上 AimToY 等于 6 所以(每个都是 3)所以最终速度将是 x=1 和 y=1,如果最终循环等于四,而不是像 x=2 和 y=2 一样结束,这很重要)

那么,问题是,如何让它变得更好?

【问题讨论】:

  • 你有什么问题?
  • 你的子弹是否匀速移动?
  • 如果您想要更高的精度,请使用双精度而不是整数。你不能指望用整数除法得到精确的结果,因为它们是……整数
  • 你想让你的子弹以一致的速度到达一个确切的位置吗?如果是这样,我有你的代码,如果你愿意,我可以将它作为答案发布

标签: java android projectile


【解决方案1】:

如果你想让子弹在任何角度以恒定速度行进,你真的想要更像这样的东西。此外,来自@JSlain 的关于使用 double 的 cmets 也很准确,即使您在绘制/渲染子弹时必须四舍五入这些值,它们也会更加准确

public double[] getSpeed(int sx, int sy, int ex, int ey)
{
    double dx = ex - sx;
    double dy = ey - sy;

    double theta = Math.atan2(dy, dx); //get the angle your bullet will travel

    int bulletSpeed = 5; //how fast your bullet can go.

    double[] speeds = new double[2];

    speeds[0] = Math.cos(theta) * bulletSpeed;
    speeds[1] = Math.sin(theta) * bulletSpeed;

    return speeds;
}

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多