2016-01-28 71 views
0

我想我的駱駝改變方向如果llama.x < 1100; 但美洲駝的方向只會改變,直到llama.x> -1100,所以它保持在-1100/-1099。我怎樣才能改變它(或直到我再次改變它)?不幸的是,迭代器中的while循環將不起作用。我試了幾個小時,但沒有找到解決方案。我希望你可以幫助我!這裏是我的代碼:Libgdx使矩形移動

private void spawnLama() { 
    Rectangle livinglama = new Rectangle(); 
    livinglama.x = -500; 
    livinglama.y = -150; 
    livinglama.width = 64; 
    livinglama.height = 64; 
    LamaXMovement = MathUtils.random(-300, 300); 
    livinglamas.put(livinglama, LamaXMovement); 
    lastLamaTime = TimeUtils.nanoTime(); 
} 

@Override 
public void render() { 
    Gdx.gl.glClearColor(110/255F, 211/255F, 43/255F, 1/255F); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
    batch.setProjectionMatrix(camera.combined); 
    elapsedTime += Gdx.graphics.getDeltaTime(); 
    if(TimeUtils.nanoTime() - lastLamaTime > 1000000000L) spawnLama(); 
    Iterator<ObjectMap.Entry<Rectangle, Integer>> iter = livinglamas.iterator(); 
    while (iter.hasNext()){ 
     ObjectMap.Entry<Rectangle, Integer> entry = iter.next(); 
     Rectangle lama = entry.key; 
     int value = entry.value; 
if(lama.x <= 1100){ 
entry.value = -10; 
value = -10: 
} 
      lama.x += value * Gdx.graphics.getDeltaTime(); 
     } 
     if(Gdx.input.isTouched()) { 
      for (Rectangle lama : livinglamas.keys()) { 
       if (lama.contains(Gdx.input.getX(), Gdx.input.getY())) { 
        money += 1; 
       } 
      } 
     } 
     batch.begin(); 
     for(Rectangle lama : livinglamas.keys()) { 
      batch.draw(animation.getKeyFrame(elapsedTime, true), lama.x, lama.y); 
     } 

... 編輯: 我想喇嘛自然移動。速度不應該一樣。首先,我希望他們在-1100轉彎,因爲這是在正交相機之外。然後,我會改進它(增加更多的位置,他們改變方向......)

+0

這是不是很清楚你想要什麼。你希望它在-1100和+1100之間來回移動?每個美洲駝的存儲速度是多少?你希望速度是相同的,當美洲駝切換方向或一切都以10的速度移動? – Tenfour04

+0

我希望喇嘛自然移動。速度不應該一樣。首先,我希望他們在-1100轉彎,因爲這是在正交相機之外。然後,我會改進它(添加更多的職位,他們改變方向......) – AlGrande

回答

3

我建議做一個Llama類來封裝駱駝的行爲。這將包括xy座標和widthheight。您還應該有一個speedvelocity值,該值可以添加到x座標中。現在您可以存儲一個Llama對象的列表,而不是您當前使用的地圖。此外,在適當的情況下,您可以將velocity從正面更改爲負面或反之,以改變方向。

附錄:

首先,我將包括在建議Llamamove()方法:

public class LlamaGame implements ApplicationListener { 
    List<Llama> llamas = new ArrayList<>(); 

    // ... 

    @Override 
    public void render() { 
    // ... 
    for (Llama llama : llamas) { 
     llama.move() 
    } 
    // ... 
    } 
} 

public class Llama { 
    private int x, y, speed; 

    void move() { 
    x += speed 
    } 
} 

現在你可以使用擴展的for循環迭代列表

最後,改變方向的邏輯可以進入move() HOD。

此外,你應該環顧一些libgdx的例子。他們中的許多人使用單獨的「渲染器」和「控制器」類來分離遊戲的這兩個組件的邏輯。

+0

謝謝!我試過這個,但我不知道如何在render()中迭代它。你能舉個例子嗎? – AlGrande