問題描述
LibGDX ‑ 只有可拖動的運動 (LibGDX ‑ only draggable movement)
:D 我目前正在為 Android 創建我的第一個 LibGDX 遊戲。而且我遇到了一個關於我的小玩家(這是一個桶;))的運動的問題。我想讓桶(播放器)只能在 x 軸上拖動,而不能點擊來改變位置。y 軸不會成為問題,因為桶只能改變 x 軸上的位置。所以我基本上想讓桶只能拖動。抱歉我的寫作,英語不是我的母語。
這是我的代碼中的代碼片段,運動在其中運行:
if (Gdx.input.isTouched()){
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
//Check the values
float touchPosX = Gdx.input.getX();
float touchPosY = Gdx.input.getY();
String touchXString = Float.toString(touchPosX);
String touchYString = Float.toString(touchPosY);
Gdx.app.log("Movement ‑ X", touchXString);
//Gdx.app.log("Movement ‑ Y", touchYString);
Gdx.app.log("Movement ‑ BucketX", bucketXString);
//Gdx.app.log("Movement ‑ BucketY", bucketYString)
camera.unproject(touchPos);
bucket.x = touchPos.x ‑ 64 / 2;;}
代碼有點亂……
參考解法
方法 1:
If I understand correctly, what you want is that the bucket only moves when you are dragging it, and right now what it does is move to whatever "x" you clicked/taped, even if that "x" is far from the bucket, thus "teleporting" it.
To do this, first have a boolean lets say, "btouched".
boolean btouched = false;
Then you will have to use an Input Processor (instead of InputPolling). to check in the touchdown event if the click/tap was inside the bucket, then only if it was, it will move in the drag event:
MyInputProcessor inputProcessor;
public class MyInputProcessor implements InputProcessor{
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button){
camera.unproject(touchPos.set(Gdx.input.getX(pointer), Gdx.input.getY(pointer), 0));
if(bucket.contains(touchPos)){
btouched = true;
}else{
btouched = false;
}
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer){
camera.unproject(touchPos.set(Gdx.input.getX(pointer), Gdx.input.getY(pointer), 0));
if(btouched){
bucket.x = touchPos.x ‑ 64 / 2;
}
return false;
}
...
}
Dont forget to set the input processor:
inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);
(by Andreas Johansson、Lestat)