在我的libgdx项目中设置精灵按钮时,如果我给出的屏幕尺寸大于我的设备,我会移动他们的触摸区域。
这是我编写的代码的一个简单示例。主要课程扩展了游戏......
public class Application extends Game
{
public SpriteBatch batch;
public OrthographicCamera camera;
public Vector3 touchPosition;
protected TitleScreen screen_title;
protected SettingsScreen screen_settings;
public PlayScreen screen_play;
@Override
public void create()
{
batch = new SpriteBatch();
camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
camera.setToOrtho(false,Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
touchPosition = new Vector3();
//SCREENS
screen_title = new TitleScreen(this);
screen_settings = new SettingsScreen(this);
screen_play = new PlayScreen(this);
this.setScreen(screen_title);
}
}
一个带有图像的简单屏幕,用于检测是否被触摸......
public TitleScreen(final Application game)
{
this.game = game;
game.camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
game.camera.position.set(Constants.VIEWPORT_WIDTH / 2, Constants.VIEWPORT_HEIGHT / 2, 0);
background = new Sprite(new Texture(Gdx.files.internal(Constants.PATH_BACKGROUND + "bg.png")));
img = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")));
}
@Override
public void render(float delta)
{
Gdx.gl.glClearColor(0.7f, 0.7f, 0.9f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.camera.update();
game.batch.setProjectionMatrix(game.camera.combined);
game.batch.begin();
background.draw(game.batch);
img.setPosition( Constants.VIEWPORT_WIDTH / 2, Constants.VIEWPORT_HEIGHT /2);
img.draw(game.batch);
game.batch.end();
//detect touch position
if(Gdx.input.justTouched())
{
game.touchPosition.set(Gdx.input.getX(), Gdx.input.getY(), 0);
game.camera.unproject(game.touchPosition);
if ((Gdx.input.getX() > img.getX()) &&
Gdx.input.getX() < img.getX() + img.getWidth() &&
Gdx.input.getY() < Gdx.graphics.getHeight() - img.getY() &&
Gdx.input.getY() > Gdx.graphics.getHeight() - (img.getY() + img.getHeight()))
{
System.out.println("TOUCHED BUTTON!!!");
System.out.println("X: " + Gdx.input.getX() + "/ Y: " + Gdx.input.getY());
}
}
}
如上所述,此代码示例在桌面(任何大小)和我的手机(如果它具有相同或更小的屏幕尺寸)中工作正常,但不是当我使用更大的视口大小时,并不真正理解为什么:)
非常感谢您的帮助:)