使用libgdx触摸代码仅在我的球类游戏屏幕的中心起作用 [英] Touch code only working at center of screen in my ball game using libgdx

查看:62
本文介绍了使用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触摸代码仅在我的球类游戏屏幕的中心起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆