2016-11-16 65 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