基本的2D路径查找(无需图表)

时间:2013-06-25 04:05:46

标签: java game-physics

我正在处理(Java的一个变种)游戏(仅仅是为了我自己的乐趣),并遇到了一个问题。我有一个由Castle类创建和管理的抛射类,它朝向Enemy类(它是一个移动目标)。我想要做的(概念上)是让这个射弹找到它的预定目标(欧几里德距离),比如它的20个单位,然后沿那条线移动5个单位(即那里的1/4)。我的问题是我不知道如何提取该向量的x和y分量来更新这个射弹的位置。这是我目前的射弹课程:

class Projectile{

  private PImage sprite;
  private Enemy target;
  private int x;
  private int y;
  private int speed;

  public Projectile(PImage s, Enemy t, int startx, int starty, int sp) throws NullPointerException{
    if(t == null){
      if(debug){
        println("Null target given to Projectile(), throwing exception");
      }
      throw new java.lang.NullPointerException("The target of the projectile is null");
    }
    sprite = s;
    target = t;
    x = startx;
    y = starty;
    speed = sp;
    if(debug){
      println("Projectile created: " + t + " starting at position: " + startx + " " + starty);
    }
  }


  public void update(){
    if(target != null){
      int goingToX = target.getCenterX() ;
      int goingToY = target.getCenterY();

      //find the total distance to the target
      float d = dist(this.x, this.y, target.getCenterX(), target.getCenterY());
      //divide it by the velocity vector
      d /= speed;

      //get the dx and dy components of the vector



    }else{//target is null, i.e. already destroyed by something else
      //destroy this projectile
      //if the higher functions were correct, then nothing needs to go here
      //this should be deleted as long as it checks for this.hitTarget()
      return;
    }
  }

  public void render(){
    image(sprite, x, y, 10, 10);
  }

  //checks if it hit the target, but does a little bit of rounding because the sprite is big
  //done this way in the interest of realism
  public boolean hitTarget(){
    if(target != null){
      if(abs(x - target.getCenterX()) <= 5 && abs(y - target.getCenterY()) <= 5 ){
        return true;
      }else{
        return false;
      }
    }
    //this activates if the target is null, which marks this for deletion
    return true;
  }
}

我一直在研究这个问题几个小时,并且当我考虑将浮点数转换为字符串,将它们格式化为一些小数位,然后尝试将其转换为我将减少的分数时,我意识到我的方法不必要地复杂化。我觉得这比我意识到的要容易得多,但我缺乏数学背景来做到这一点。所有必要的更改只需要在Projectile.update()中完成。谢谢!

1 个答案:

答案 0 :(得分:3)

假设您希望您的射弹“跟踪”目标,那么您可以使用一个简单的触发位来计算x和y的相对速度:

//Calculate the differences in position
float diffX = target.getCenterX() - this.x;
float diffY = target.getCenterY() - this.y;

//Calculate the angle
double angle = Math.atan2(diffY, diffX);

//Update the positions
x += Math.cos(angle) * speed;
y += Math.sin(angle) * speed;

这基本上计算了射弹和目标之间的角度,然后根据给定的速度将射弹向该方向移动。