我尝试寻找解决问题的答案,但我认为我似乎不明白如何在Libgdx中使用长按。
我希望我的角色在长按屏幕右半部分时向右移动,在长按屏幕左半部分时向左移动。
我已经搜索并尝试过。
这是我的InputHandler类:
public class InputHandler implements InputProcessor {
private MainCharacter myMainCharacter;
public InputHandler(MainCharacter mainCharacter) {
myMainCharacter = mainCharacter;
}
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
myMainCharacter.onClick();
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
}
这是我的MainCharacter类(class):
public class MainCharacter {
private Vector2 position;
private Vector2 velocity;
private Vector2 acceleration;
private float rotation;
private int width;
private int height;
public MainCharacter(float x, float y, int width, int height) {
this.width = width;
this.height = height;
position = new Vector2(x, y);
velocity = new Vector2(0, 0);
acceleration = new Vector2(0, 460);
}
public void update(float delta) {
velocity.add(acceleration.cpy().scl(delta));
if (velocity.y > 200) {
velocity.y = 200;
}
position.add(velocity.cpy().scl(delta));
}
public void onClick() {
if (Gdx.input.getX() <= 135) {
Gdx.app.log("TAG", "LEFT");
position.x--;
} else if (Gdx.input.getX() >= 137) {
Gdx.app.log("TAG", "RIGHT");
position.x++;
}
}
public float getX() {
return position.x;
}
public float getY() {
return position.y;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public float getRotation() {
return rotation;
}
}
我使用 onClick()
方法作为替代方法,直到找到问题的解决方案。它工作正常,但没有与长按相同的效果。当我单击屏幕左侧时,我的角色向左移动;当我单击屏幕右侧时,我的角色向右移动。但当然,当我长按时它不起作用。
那么我该如何使用“长按”呢?
我非常感谢您的帮助。
最佳答案
Gokul 很好地概述了 GestureListener,但我不相信这就是您正在寻找的。 长按
确实只有在按下几秒钟后才会注册,并且您希望立即触摸控制角色。
监听器中没有开箱即用的方法来持续检测触摸,但您可以自己创建它。
if (Gdx.input.isTouched())
{
//Finger touching the screen
// You can actually start calling onClick here, if those variables and logic you are using there are correct.
if (Gdx.input.getX() >= screenSize / 2)
{
//Right touched
}
else if (Gdx.input.getX() < screenSize / 2)
{
//Left touched
}
}
只需检查每一帧并执行您的逻辑即可。
关于java - Libgdx - 如何使用 "Long Press"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42241297/