代码之家  ›  专栏  ›  技术社区  ›  Niranjana

如何移动类似正弦波运动的物体-LibGdx

  •  1
  • Niranjana  · 技术社区  · 7 年前

    enter image description here

    我这样移动我的物体:

    public void moveLeavesDown(float delta) {
    
        setY(getY() - (getSpeed()* delta));
    
    }
    

    我怎样才能得到这种运动?

    1 回复  |  直到 7 年前
        1
  •  1
  •   dfour    7 年前

    您可以添加计时器并使用数学。sin函数为叶子添加偏移量。

    下面的演示演示了如何完成此操作:

    import com.badlogic.gdx.ApplicationAdapter;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.GL20;
    import com.badlogic.gdx.graphics.g2d.SpriteBatch;
    import com.badlogic.gdx.graphics.g2d.TextureRegion;
    import com.badlogic.gdx.math.Vector2;
    
    public class Test extends ApplicationAdapter{
    
        float time =0; // timer to store current elapsed time
        Vector2 leaf = new Vector2(150,150); // holds the leaf x,y pos
        float sinOffset = 0; // the offset for adding to the image
        private SpriteBatch sb; // spritebatch for rendering
        TextureRegion tx;  // a texture region(the leaf)
    
    
        @Override
        public void create() {
            sb = new SpriteBatch(); // make spritebatch
            tx = DFUtils.makeTextureRegion(10, 10, "FFFFFF"); // makes a textureRegion of 10x10 of pure white
    
        }
    
        @Override
        public void render() {
            // clear screen
            Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
            leaf.y = leaf.y-0.2f; // move downwards
            time+= Gdx.graphics.getDeltaTime(); // update sin timer
            sinOffset =(float)Math.sin(time)*10; // calculate offset
    
            // draw leaf with offset
            sb.begin();
            sb.draw(tx, leaf.x+sinOffset, leaf.y);
            sb.end();
    
        }
    }