我触球后得分没有增加.仅当我触摸球及其靠近屏幕中心的位置时,它才会增加.
当我的球仅沿x轴移动并保持y不变时,触摸效果很好.但是,当两者都增加时,仅在中央触摸时分数会增加.
@Override
public void render () {
batch.begin();
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(ball,xposi,yposi,100,100);
if(gameState==1) {
if (Gdx.input.justTouched()) {
tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
textureBounds = new Rectangle(xposi, yposi, 100, 100);
if (textureBounds.contains(tmp.x, tmp.y)) {
Gdx.app.log("Click", "On Ball");
score++;
}
else {
Gdx.app.log("Click", "Not on Ball");
}
}
font.draw(batch, String.valueOf(score), 100, 300);
font.draw(batch, String.valueOf(lives), 200, 300);
xposi+=velocity;
yposi+=velocity;
if (xposi >= xmax - 100) {
velocity = -velocity;
} else if (xposi <= xmin) {
velocity = -velocity;
}
if (yposi >= ymax - 100) {
velocity = -velocity;
} else if (yposi <= ymin) {
velocity = -velocity;
}
batch.end();
}
}
最佳答案
在libgdx中,当我们在屏幕上绘制某些东西时,屏幕原点是左下角,但是当我们检测到触摸时,屏幕原点是左上角.
当您处理水平运动时,则不会涉及y坐标,因此可以正常工作.当您的球居中时,您会检测到对球的触摸,然后Gdx.input.getY()的值与Gdx.graphics.getHeight()-Gdx.input.getY()大致相同,因此有时可以使用.
如此简单的解决方案就是将触摸坐标原点反转到左下角.
tmp = new Vector3(Gdx.input.getX(),Gdx.graphics.getHeight()-Gdx.input.getY(), 0);
建议:
不要像在创建Rectangle和Vector3的对象那样在render方法中创建对象,不要在show()或create()方法中创建对象,并在render()方法中将值设置为这些变量.