問題描述
在過去的幾天里,我一直在將我的游戲 (Apopalypse) 移植到 Android 移動平臺.我在谷歌上快速搜索了精靈觸摸檢測,但沒有發(fā)現(xiàn)任何有用的東西.每個氣球一旦被觸摸就會彈出,我只需要檢測它是否被觸摸.這是我的氣球生成代碼:
In the past few days I've been porting my game (Apopalypse) to the Android Mobile platform. I've did a quick search on Google of sprite touch detection but didn't find anything helpful. Each balloon will pop once touched and I just need to detect if it's touched. Here's my balloon spawning code:
渲染(x、y、寬度和高度是隨機(jī)的):
Rendering (x, y, width, and height are randomized):
public void render() {
y += 2;
balloon.setX(x);
balloon.setY(y);
balloon.setSize(width, height);
batch.begin();
balloon.draw(batch);
batch.end();
}
在主游戲類中生成:
addBalloon(new Balloon());
public static void addBalloon(Balloon b) {
balloons.add(b);
}
推薦答案
我就是這樣做的,但是根據(jù)您使用的場景和可以觸摸的元素,可以有稍微更優(yōu)化的方法來執(zhí)行此操作:
This is how I did it, but depending on the scene you are using and the elements that can be touched, there can be slightly more optimized ways of doing this:
public GameScreen implements Screen, InputProcessor
{
@Override
public void show()
{
Gdx.input.setInputProcessor(this);
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
for(int i = 0; i < balloons.size(); i++)
{
if(balloons.get(i).contains(pointerX, pointerY))
{
balloons.get(i).setSelected(true);
}
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
for(int i = 0; i < balloons.size(); i++)
{
if(balloons.get(i).contains(pointerX, pointerY) && balloons.get(i).getSelected())
{
balloons.get(i).execute();
}
balloons.get(i).setSelected(false);
}
return true;
}
public class InputTransform
{
private static int appWidth = 480;
private static int appHeight = 320;
public static float getCursorToModelX(int screenX, int cursorX)
{
return (((float)cursorX) * appWidth) / ((float)screenX);
}
public static float getCursorToModelY(int screenY, int cursorY)
{
return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
}
}
這篇關(guān)于如何檢測 Java libGDX 中是否觸摸了精靈?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!