java - 使 Sprite 沿 vector 的相反方向移动

标签 java libgdx

我有一个从屏幕左下角移动到右上角的 Sprite 。我想知道的是我如何让它掉头朝相反的方向走,并继续这个循环。

我尝试否定 vector 的方向,但这不起作用。

这就是我现在所拥有的:

public void create() {
    // Game Initialization  
    v = new Vector2(Gdx.graphics.getWidth() - 0, Gdx.graphics.getHeight() - 0); 
    v.nor();
    v.scl(100);

    spriteBatch = new SpriteBatch(); 
    bug = new Sprite(new Texture("EnemyBug.png"));
    bug.setSize(50, 85);
    bug.setOrigin(0,0);//Gdx.graphics.getHeight() / 5, Gdx.graphics.getHeight() / 5);
    bug.setPosition(1,1);//Gdx.graphics.getWidth() - 50, Gdx.graphics.getHeight() - 50);
    bug.rotate(v.angle());

    rotDeg = 5;
}

@Override
public void render() {
    // Game Loop

    Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();        

    if(bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100)){
        turn = !turn;
    }
    else if(bug.getX() <= 50 && bug.getY() <= 50){
        turn = !turn;
    }


    if(!turn){          
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    bug.draw(spriteBatch);
    spriteBatch.end();
}

最佳答案

您每帧将 Sprite 平移两次:

if(!turn){          
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    //REMOVE THIS LINE
    bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());

额外的一行可能会导致您的问题,使您的负面翻译无效并使正面翻译加倍。

关于java - 使 Sprite 沿 vector 的相反方向移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684275/

相关文章:

java - 警告 : "sun.reflect.Reflection.getCallerClass is not supported. This will impact performance"

java - 有没有一种方法可以在Maven构建环境中使用Gradle API?

java - 在mybatis中传递数据库名称

java - 带有jlist的keylistener

android - LibGdx - 在 Sprite 中处置 Sprite 或纹理是强制性的吗?

java - 尝试在本地存储上读取/写入时出现 ".txt file not found"- Libgdx,Android studio

Java 发布工程良好实践

java - Picasso Android 内存问题,当 fragment 被替换时

java - 绘制网格和纹理 libgdx

java - Libgdx Android 应用程序在启动时崩溃