将触摸区域限制为libgdx中的“纹理"区域 [英] Limit touch area to Texture area in libgdx

查看:110
本文介绍了将触摸区域限制为libgdx中的“纹理"区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载纹理并将其转换为精灵.下图显示了典型精灵的外观.精灵的形状各不相同.当用户仅触摸表面区域时,我就不会移动这些精灵.目前,我正在使用矩形边界来检测用户是否触摸了它.此方法不干净,因为纹理不是矩形.结果,用户可以拖动它而无需精确地触摸它.问题是如何创建一个仅代表纹理区域的触摸区域(即下图中的非透明像素区域或排除灰色区域).

I load textures and convert them to sprites. The image below shows how typical sprite looks like. The shapes varies from sprites to sprite. I wont to move these sprites when user touches just the surface area. Currently I am using rectangle bounds to detect if user touched it or not. This approach is not clean becuase the texture is not a rectangle. As a consequence users can drag it without precisely touching it. The question is how to create a touch area just to represent the texture area (that is non-transparent pixel area or exclude gray color area in the image below).

推荐答案

我将通过颜色选择来解决这个问题.首先确定子画面上的哪个像素被触摸,然后检查触摸的像素是否透明.使用选自此问题的代码,并做了一些改动(不是经过测试):

I would approach this with color picking. By first determining which pixel on the sprite is touched and then check if the touched pixel is transparent. With code taken from this question and altered a bit (not tested):

Color pickedColor = null;
Rectangle spriteBounds = sprite.getBoundingRectangle();
if (spriteBounds.contains(Gdx.input.getX(), Gdx.input.getY())) {
    Texture texture = sprite.getTexture();

    int spriteLocalX = (int) (Gdx.input.getX() - sprite.getX());
    // we need to "invert" Y, because the screen coordinate origin is top-left
    int spriteLocalY = (int) ((Gdx.graphics.getHeight() - Gdx.input.getY()) - sprite.getY());

    int textureLocalX = sprite.getRegionX() + spriteLocalX;
    int textureLocalY = sprite.getRegionY() + spriteLocalY;

    if (!texture.getTextureData().isPrepared()) {
        texture.getTextureData().prepare();
    }
    Pixmap pixmap = texture.getTextureData().consumePixmap();
    pickedColor = new Color(pixmap.getPixel(textureLocalX, textureLocalY));
}

//Check for transparency
if (pickedColor != null && pickedColor.a != 0) {
    //The picked pixel is not transparent, the nontransparent texture shape was touched
}

请记住,这尚未经过测试,可能可以进行优化.

Have in mind this hasn't been tested and can probably be optimized.

这篇关于将触摸区域限制为libgdx中的“纹理"区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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