[英]Java 2D Game 'Grid Movement'
我正在使用libGDX嘗試制作一個自上而下的2D游戲,並沿口袋妖怪的路線移動。 但是,我不確定如何實現這一點。
我希望玩家能夠按下某個鍵(例如:箭頭鍵或WASD)來移動,但是,當玩家釋放鍵時,我不希望角色停止移動,直到其位置沿着網格下降由32x32像素正方形組成的單元數。
那么,我將如何創建一個32x32像素單元的“不可見”網格並使我的角色僅在它們位於其中一個單元上方時才停止移動?
到目前為止,我只完成了逐像素移動。 我已經考慮過要說一個布爾值來說明角色是否在移動,並且如果該角色降落在正確的區域上就可以改變它,但是我還沒有想到實現該目標的任何方法。
這是我用於逐像素移動的方法(libGDX涵蓋了按鍵輸入,並根據玩家的邊界框所在的位置繪制了子畫面):
public void generalUpdate() {
if(Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)) {
if (anim_current == Assets.anim_walkingLeft)
if(player.collides(wall.bounds)) {
player.bounds.x += 1;
}
else
player.dx = -1;
else
anim_current = Assets.anim_walkingLeft;
Assets.current_frame = anim_current.getKeyFrame(stateTime, true);
}
else if (Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT)) {
if (anim_current == Assets.anim_walkingRight)
if(player.collides(wall.bounds)) {
player.bounds.x -= 1;
}
else
player.dx = 1;
else
anim_current = Assets.anim_walkingRight;
Assets.current_frame = anim_current.getKeyFrame(stateTime, true);
}
else if (Gdx.input.isKeyPressed(Keys.W) || Gdx.input.isKeyPressed(Keys.UP)) {
if (anim_current == Assets.anim_walkingUp)
if(player.collides(wall.bounds)) {
player.bounds.y += 1;
}
else
player.dy = -1;
else
anim_current = Assets.anim_walkingUp;
Assets.current_frame = anim_current.getKeyFrame(stateTime, true);
}
else if (Gdx.input.isKeyPressed(Keys.S) || Gdx.input.isKeyPressed(Keys.DOWN)) {
if (anim_current == Assets.anim_walkingDown)
if(player.collides(wall.bounds)) {
player.bounds.y -= 1;
}
else
player.dy = 1;
else
anim_current = Assets.anim_walkingDown;
Assets.current_frame = anim_current.getKeyFrame(stateTime, true);
}
else {
Assets.current_frame = anim_current.getKeyFrames()[0];
player.dx = player.dy = 0;
}
player.bounds.x += player.dx;
player.bounds.y += player.dy;
}
您的代碼非常混亂,我不想嘗試對其進行修復,但是通常可以通過以下方法解決問題:
如果要移動,請使用布爾值表示。 我們稱之為isMoving
。 也有一種存儲方向的方法(可能是0到3之間的整數)。 我們稱它為dir
。
當您按一個鍵時,將isMoving
設置為true。 如果您與網格對齊,則將dir
更新為您按下的鍵的方向。
如果不按住鍵,請將isMoving
設置為false。
當您移動角色時,如果isMoving
為true並且它們未與網格對齊,則移動是由dir
表示的方向。 如果它們與網格對齊, isMoving
設置為false並且不移動。
// Only including one key, process is same for others.
if (rightKey) {
isMoving = true;
if (aligned)
dir = 0;
} /* chain other keys in here */ else {
isMoving = false;
}
if (isMoving) {
if (!aligned) {
move(dir);
render(dir);
} else {
}
}
我只是意識到快要結束了,它可能無法在當前狀態下工作:/。 我希望這至少可以使您知道該怎么做。 我會嘗試對其進行更多修改...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.