Touch code only working at center of screen in my ball game using libgdx(触摸代码仅在我的球赛中使用 libgdx 的屏幕中心工作)
问题描述
触球后我的分数没有增加.仅当我触摸球及其靠近屏幕中心时它才会增加.当我的球只在 x 轴上移动并保持 y 不变时,触摸效果很好.但是当两者都增加时,只有在触摸中心时分数才会增加.
My score does not increment after I touch the ball. It increments only when I touch the ball and its near the center of my screen. When my ball only moves in x axis keeping y constant the touch works fine. But when both are incremented the score increases only when touched at the center.
@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 中,当我们在屏幕上绘制东西时,屏幕原点是左下角,但当我们检测到触摸时,屏幕原点是左上角.
In libgdx, when we draw something on screen then the screen origin is bottom left corner but when we detect touch then screen origin is top left corner.
当您处理水平移动时,不会涉及 y 坐标,因此可以正常工作.当你的球在中心时你检测到球的触摸,那么 Gdx.input.getY()
的值与 Gdx.graphics.getHeight()-Gdx.input.getY()
所以有时可以.
When you deal with horizontal movement then there is no involvement of y coordinate so it's work fine. You detect touch on ball when your ball is in center then the value of Gdx.input.getY()
is approximately same to Gdx.graphics.getHeight()-Gdx.input.getY()
so sometimes works.
如此简单的解决方案就是将触摸坐标原点反转到左下角.
so simple solution is just invert touch coordinate origin to bottom left corner.
tmp = new Vector3(Gdx.input.getX(),Gdx.graphics.getHeight()-Gdx.input.getY(), 0);
建议:
不要像创建 Rectangle 和 Vector3 的对象那样在 render 方法中创建对象,在 show()
或 create()
方法中创建对象并设置值render()
方法中的这些变量.
Don't create object in render method like you're creating object of Rectangle and Vector3, create object in show()
or create()
method and set value to these variable in render()
method.
这篇关于触摸代码仅在我的球赛中使用 libgdx 的屏幕中心工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:触摸代码仅在我的球赛中使用 libgdx 的屏幕中


- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01