制作两个半径为 8 的圆(图像 16x16) 和半径 20 之一(图像 40x40) 我正在调用 circle over overlap 方法并且 collsion 刚刚关闭。它与我的球图像所在位置的 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();
}
}
}
}
最佳答案
如果你的子弹和球是 2 个圆圈,就像你说的那样你不需要重叠方法。
很简单:两个圆相撞,如果它们的距离小于它们的半径之和。
要计算平方根所需的距离。这是一个相当昂贵的计算,所以最好使用距离的平方和半径的平方和:
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
中,您写了一个 cooment:
//true starts top right false starts top left
错了,是左上角还是左下角。默认情况下它位于左下角,因为这是坐标系正常工作的方式。左上角是,因为监视器从左上角开始寻址像素 = 像素 1。
编辑: 这应该是问题所在:您给 batch.draw
方法的坐标是 Texture
的左下角默认情况下,如果您使用的是“y = Down”-系统,它应该在左上角(您必须尝试我不确定)。
Circle
的位置是它的中心。
要解决这个问题,您需要像这样调整位置(对于“y = Up”-System):
batch.draw(bulletImage, bullet.x - bullet.radius, bullet.y - bullet.radius);
有可能,相同的公式也适用于“y = Down”系统,但我不确定
关于java - 简单的圆圈碰撞 libgdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24176690/