在我试图制作的游戏中,用户可以使用虚拟操纵杆移动玩家,就像许多手机游戏一样。当手指放在屏幕上然后沿一个方向移动时(手指移动的距离不能产生差异),这会使玩家朝那个方向移动。
我在执行此操作时遇到了问题。当手指被拖动到屏幕的另一侧时,播放器仅朝向正确的方向。我认为问题在于屏幕上的touchDown和touchDragged发生了。如何使touchPosition独立于屏幕上的位置?
这是我的代码,prevTouchPoint
是为了解决当手指不再移动但仍然在屏幕上时,播放器仍然朝着正确的方向移动。 position
是玩家的位置。
public void update(float delta) {
if(moving) {
Vector2 dif = touchPoint.sub(startPoint);
touchPoint.set(prevTouchPoint);
dif.nor();
position.add(dif);
}
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
startPoint = viewport.unproject(new Vector2(screenX, screenY));
moving = true;
Gdx.app.log("Player", "TouchDown");
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
moving = false;
startPoint.set(0, 0);
touchPoint.set(0, 0);
prevTouchPoint.set(0, 0);
Gdx.app.log("Player", "TouchUp");
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
if(moving) {
touchPoint = viewport.unproject(new Vector2(screenX, screenY));
prevTouchPoint.set(touchPoint);
Gdx.app.log("Player", "TouchDragged");
return true;
}
else {
return super.touchDragged(screenX, screenY, pointer);
}
}
谢谢
答案 0 :(得分:1)
尝试这种方式:
public class GdxTest extends ApplicationAdapter implements InputProcessor{
ExtendViewport viewport;
SpriteBatch batch;
Sprite sprite;
Texture texture;
Vector2 touchDown,drag,spritePos;
@Override
public void create() {
viewport=new ExtendViewport(400,640);
touchDown =new Vector2();
drag =new Vector2();
spritePos=new Vector2();
batch=new SpriteBatch();
sprite=new Sprite(texture=new Texture("badlogic.jpg"));
sprite.setSize(100,100);
Gdx.input.setInputProcessor(this);
}
@Override
public void render() {
Gdx.gl.glClearColor(1,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
if(Gdx.input.isTouched()){
Vector2 diff= drag.cpy().sub(touchDown);
diff.nor();
touchDown.set(drag);
spritePos.add(diff.scl(3));
}
sprite.setPosition(spritePos.x-sprite.getWidth()/2,spritePos.y-sprite.getHeight()/2);
}
@Override
public void resize(int width, int height) {
viewport.update(width,height);
}
@Override
public void dispose() {
texture.dispose();
batch.dispose();
}
@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) {
touchDown.set(screenX,screenY);
viewport.unproject(touchDown);
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
touchDown.set(0,0);
drag.set(0,0);
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
drag.set(screenX,screenY);
viewport.unproject(drag);
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
}