[英]simple Circle on circle Collision libgdx
做了兩個半徑為8的圓(圖像16x16)和半徑為20(圖40x40)之一的圓,我稱此圓為重疊法,並且碰撞剛剛結束。 它與一個圓圈碰撞,該圓圈位於我的球形象所在的0,0點附近。 子彈可以在球的底部和右側進入。
public class MyGame extends ApplicationAdapter {
SpriteBatch batch;
Texture ballImage, bulletImage;
OrthographicCamera cam;
Circle ball;
Array <Circle> bullets;
long lastShot;
@Override
public void create ()
{
System.out.println("game created");
ballImage = new Texture(Gdx.files.internal("ball.png"));
bulletImage = new Texture(Gdx.files.internal("bullet.png"));
cam = new OrthographicCamera();
cam.setToOrtho(true,320,480);//true starts top right false starts top left
batch = new SpriteBatch();
ball = new Circle();
ball.radius=20;
ball.x=320/2-ball.radius; // half screen size - half image
ball.y=480/2-ball.radius;
bullets = new Array<Circle>();
spawnBullet();
/*
batch.draw(bulletImage,bullet.x,bullet.y);
bullet.x++;
bullet.y++; */
}
public void spawnBullet()
{
Circle bullet = new Circle();
bullet.radius=8;
bullet.x=0;
bullet.y=0;
bullets.add(bullet);
lastShot = TimeUtils.nanoTime();
}
@Override
public void render ()
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
batch.draw(ballImage,ball.x,ball.y);
for(Circle bullet: bullets)
{
batch.draw(bulletImage, bullet.x, bullet.y);
}
batch.end();
if(Gdx.input.isTouched())
{
Vector3 pos = new Vector3();
pos.set(Gdx.input.getX(), Gdx.input.getY(),0);
cam.unproject(pos);
ball.y = pos.y - ball.radius;
ball.x = pos.x - ball.radius ;
}
//if(TimeUtils.nanoTime()-lastShot >1000000000) one second
//spawnBullet();
Iterator<Circle> i = bullets.iterator();
while(i.hasNext())
{
Circle bullet = i.next();
bullet.x++;
bullet.y++;
if(bullet.overlaps(ball))
{
System.out.println("overlap");
i.remove();
}
}
}
}
如果子彈和球是兩個圓圈,就像您說的那樣,您不需要重疊方法。
很簡單:兩個圓發生碰撞,如果它們的距離較小,則它們的半徑之和。
要計算距離,您需要制作平方根。 這是一個相當昂貴的計算,因此最好使用距離的平方和半徑的平方和:
float xD = ball.x - bullet.x; // delta x
float yD = ball.y - bullet.y; // delta y
float sqDist = xD * xD + yD * yD; // square distance
boolean collision = sqDist <= (ball.radius+bullet.radius) * (ball.radius+bullet.radius);
而已。
同樣在cam.setToOrtho
您編寫了一個提示:
// true從右上方開始false從左上方開始
沒錯,它在左上方或左下方。 默認情況下,它位於左下角,因為這是坐標系正常工作的方式。 左上角是,因為監視器尋址從左上角=像素1開始的像素。
編輯:這應該是問題所在:默認情況下,您給batch.draw
方法指定的坐標是Texture
的左下角,如果您使用的是“ y = Down” -System,則它應該是左上角(您有嘗試我不確定)。
相反, Circle
的位置是其中心。
要解決此問題,您需要像這樣調整位置(對於“ y =向上”-系統):
batch.draw(bulletImage, bullet.x - bullet.radius, bullet.y - bullet.radius);
可能相同的公式也適用於“ y = Down”系統,但是我不確定
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.