我正在处理(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() 中完成。谢谢!