Processing (Java のバリアント) で (自分の楽しみのためだけに) ゲームに取り組んでいて、問題が発生しました。Castle クラスによって作成および管理される発射物クラスがあり、敵クラス (移動ターゲット) に向かっています。私が(概念的に)やろうとしているのは、この発射体が意図したターゲット(ユークリッド距離)を見つけ、たとえば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() でのみ行う必要があります。ありがとう!