我有一个视频游戏,箭头在箭头旋转后朝向指向的一侧移动,例如:
我需要将精灵移动到箭头指向旋转后的相同方向。 一点代码正如我试图做的那样:
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 :(得分:1)
最简单的方法是使用旋转量的正弦和余弦来确定平移向量的x和y分量。
答案 1 :(得分: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);
}
请注意,最后一段代码可能正是用户不存在所指的内容。
(如果您正在学习LibGDX和游戏开发,我推荐这本书。这非常好。)
另见:
答案 2 :(得分: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);