触摸代码仅在我的球赛中​​使用 libgdx 的屏幕中

Touch code only working at center of screen in my ball game using libgdx(触摸代码仅在我的球赛中​​使用 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 的屏幕中

基础教程推荐