如何让ParallaxBackground中的实体在AndEngine中垂直移动?

时间:2014-03-26 23:17:12

标签: java graphics andengine parallax

标题说明了一切,目前我正在制作一个我的角色垂直移动的游戏,我希望Parallax Background实体也这样做,我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是扩展ParallaxBackground类中包含的ParallaxEntity并使其垂直移动,这里有一些代码显示我是如何做到的。它基本上将x坐标的变化交换为y坐标。我已将其改编为当前版本的AndEngine,可以找到针对旧版本的原始版本代码here

import org.andengine.engine.camera.Camera;
import org.andengine.entity.IEntity;
import org.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.andengine.opengl.util.GLState;

public class VerticalParallaxEntity extends ParallaxEntity 
{
    final float mParallaxFactor;
    final IEntity mEntity;

    public VerticalParallaxEntity(final float pParallaxFactor, final IEntity pEntity) 
    {
        super(pParallaxFactor, pEntity);
        this.mParallaxFactor = pParallaxFactor;
        this.mEntity = pEntity;
    }

    public void onDraw(final GLState pGLState, final Camera pCamera, final float pParallaxValue) 
    {
        pGLState.pushModelViewGLMatrix();
        {
            final float cameraHeight = pCamera.getHeight();
            final float entityHeightScaled = this.mEntity.getHeight() * this.mEntity.getScaleY();

            float baseOffset = (pParallaxValue * this.mParallaxFactor) % entityHeightScaled;

            while(baseOffset > 0) {
                baseOffset -= entityHeightScaled;
            }
            pGLState.translateModelViewGLMatrixf(0, baseOffset, 0);

            float currentMaxY = baseOffset;

            do 
            {
                this.mEntity.onDraw(pGLState, pCamera);
                pGLState.translateModelViewGLMatrixf(0, entityHeightScaled, 0);
                currentMaxY += entityHeightScaled;
            } while(currentMaxY < cameraHeight);
        }
        pGLState.popModelViewGLMatrix();
    }
}