基本的に過去1年半の間、私はこのボックスの男(プレーヤー)を得ようとしていました。別のボックスと衝突したとき、それは一種の成功ですが、私が上に移動して、プレーヤーの左側のボックスに当たったら、それは衝突して飛んでいるボックスに入るかもしれません。それはあらゆる方向で同じです。Java 2Dの衝突検出が正しく機能していない
public int checkCollision(ID id){
for(int i = 0; i < handler.obj.size(); i++){ //Cycles through all the objects
GameObject go = handler.obj.get(i); //Stores a temp GameObject
if(go.getID() == id){ //Checks if the id matches and if so do the collision stuff.
if(getBoundsT().intersects(go.getBounds())){
System.out.println("collided top");
y = go.getY() + go.getHeight();
velY = 0;
return 0; //Top side
}
if(getBoundsB().intersects(go.getBounds())){
System.out.println("collided bottom");
y = go.getY() - height;
velY = 0;
return 1; //Bottom side
}
if(getBoundsL().intersects(go.getBounds())){
x = go.getX() + width;
velX = 0;
System.out.println("collided left");
return 2; //Left Side
}
if(getBoundsR().intersects(go.getBounds())){
System.out.println("collided right");
x = go.getX() - width;
velX = 0;
return 3; //Right Side
}
if(getBounds().intersects(go.getBounds())){
System.out.println("collided on all sides");
return 4; //All the sides
}
}
}
return 5; //No Collision
}
checkCollisionメソッドは毎秒60回呼び出されます。 getBounds(l/r/u/d)関数は、文字に対応する左、右、上(上)または下(下)の矩形を返します。 Idはちょうどプレーヤーが衝突しているものです。このシナリオでは、それは壁ですので、それはただの壁です。 (私は長方形が想定されている領域から外れないようにしています)
私は考えることができるすべてのことを試しました。 (ひどく書かれていると、これは私の最初の質問です)
編集:交差コード(getBounds)これは、すべてのオブジェクトが継承するGameObjectクラスです。
public Rectangle getBoundsB() {
return new Rectangle((int)(x + (width/2) - (width/4)), (int)(y + height/2), (int)(width/2), (int)(height/2));
}
public Rectangle getBoundsT() {
return new Rectangle((int)(x + (width/2) - (int)(width/4)), (int) y, (int)width/2, (int)(height/2));
}
public Rectangle getBoundsR() {
return new Rectangle((int)(x + width - 5), (int)(y + 5), 5, (int)(height - 10));
}
public Rectangle getBoundsL() {
return new Rectangle((int)x, (int)(y + 5), 5, (int)(height - 10));
}
public Rectangle getBounds() {
return new Rectangle((int)x, (int)y, (int)width, (int)height);
}
と(60秒ごとに呼ばれる)ティック法において:
checkCollision(ID.Wall);
交差点が発生しているかどうかを確認していますか。複数の点で交差し、一致する最初のif文が返されるように指定することができます。したがって、左とボトムに関心がある場合は、ボトムを最初に戻す可能性があります。 – Brion
私はプレーヤーの左側がオブジェクトの衝突ボックスと交差しているかどうかをチェックしています。もしそうならx動きとx速度を止めます。私はxをyに置き換えた上下のものを除いて、それぞれの側でこれをやっています。 – Cornchip
左端が右端と交差しているかどうかだけ確認していますか?または、左端が任意の端と交差する場合はどうしますか? – Brion