2016-11-16 64 views
2

我有一個視頻遊戲,其中一個箭頭朝它指向的一側移動,旋轉後的方向,例如:如何在旋轉後移動Sprite在指示的方向? Libgdx - 爪哇 - 安卓

enter image description here

我需要移動精靈一樣旋轉後箭頭指向的方向。 代碼位當我試圖做的事:

int count = 0; 
@Override 
protected void handleInput() { 
    if(Gdx.input.justTouched()){ 
     // move to the direction of pointing: 
     arrow.setPosition(x, y); 
    } 

} 

public void update(float dt){ 

    count++; 
    // rotate sprite: 
    arrow.setRotation(count); 

} 
+0

你想實現什麼?在移動精靈的同時旋轉它,或者先旋轉精靈然後移動它? – Draz

回答

1

最簡單的方法是使用旋轉量的正弦和餘弦來確定平移矢量的x和y分量。

1

在「使用LibGDX開始Java遊戲開發」一書中,作者製作了一個遊戲,我想可以演示您想要的行爲。遊戲是第3章的「海星收藏家」。玩家移動一隻烏龜來收集海星。左右箭頭鍵旋轉烏龜,向上箭頭鍵使烏龜朝當前方向前進。

遊戲的源代碼可以從作者的Github賬戶here下載。 (我不知道他爲什麼把它放在一個zip文件)。

相關的代碼如下所示:

@Override 
public void update(float dt) { 
    // process input 
    turtle.setAccelerationXY(0, 0); 

    if (Gdx.input.isKeyPressed(Keys.LEFT)) { 
     turtle.rotateBy(90 * dt); 
    } 
    if (Gdx.input.isKeyPressed(Keys.RIGHT)) { 
     turtle.rotateBy(-90 * dt); 
    } 
    if (Gdx.input.isKeyPressed(Keys.UP)) { 
     turtle.accelerateForward(100); 
    } 
    // ... 

turtle延伸擴展Actor一些自定義類。

accelerateForward的代碼如下所示:

public void accelerateForward(float speed) { 
    setAccelerationAS(getRotation(), speed); 
} 

然後爲setAccelerationAS的代碼如下所示:

// set acceleration from angle and speed 
public void setAccelerationAS(float angleDeg, float speed) { 
    acceleration.x = speed * MathUtils.cosDeg(angleDeg); 
    acceleration.y = speed * MathUtils.sinDeg(angleDeg); 
} 

注意這個代碼最後一位可能正是用戶unexistential被指的是。

(我推薦這本書,如果你正在學習LibGDX與遊戲的發展這是非常不錯的。)

參見:

0

我解決了這個頁面:enter link description here

 float mX = 0; 
float mY = 0; 
int velocity = 5; 
private float posAuxX = 0; 
private float posAuxY = 0; 
int count = 0; 
public void update(float dt){ 
    count2++; 
    flecha.setRotation(count2); 
    if (count2 >= 360){ 
     count2 = 0; 
    } 
    position = new Vector2((float) Math.sin(count2) * velocity, 
      (float) Math.cos(count2 * velocity)); 
    mX = (float) Math.cos(Math.toRadians(flecha.getRotation())); 
    mY = (float) Math.sin(Math.toRadians(flecha.getRotation())); 
    position.x = mX; 
    position.y = mY; 
    if (position.len() > 0){ 
     position = position.nor(); 
    } 
    position.x = position.x * velocity; 
    position.y = position.y * velocity; 
    posAuxX = flecha.getX(); 
    posAuxY = flecha.getY(); 

}

flecha.setPosition(posAuxX,posAuxY);

+0

如果它解決了您的問題,您應該將您的答案標記爲正確。 – DavidS