Android AndEngine生成随机精灵奇怪的问题

时间:2014-02-24 12:23:17

标签: java android andengine

首先我开始加载资源

                this.mTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 130, 130);
                this.m1TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p1.png", 0, 0);
                this.m2TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p2.png", 0, 0);
                this.m3TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p3.png", 0, 0);
                this.m4TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p4.png", 0, 0);
                this.mTextureAtlas.load();

然后我做

int x;
                x = MathUtils.random(1, 4);
                Log.e("euatl", "is" + x);

                p = null;

                if(x == 1){
                    p = new Sprite(mCameraWidth-pX, pY, this.mB1TextureRegion, this.getVertexBufferObjectManager());
                } else if(x == 2){
                    p = new Sprite(mCameraWidth-pX, pY, this.m2TextureRegion, this.getVertexBufferObjectManager());         
                } else if(x == 3){
                    p = new Sprite(mCameraWidth-pX, pY, this.mB3TextureRegion, this.getVertexBufferObjectManager());

                } else if(x == 4){
                    p = new Sprite(mCameraWidth-pX, pY, this.m4TextureRegion, this.getVertexBufferObjectManager()); 
                }

                    mScene.attachChild(p);

目前始终是p4精灵产生的,TextureAtlas中的最后一个。我的logcat说x有时是1,2,3和4,但是在手机中,精灵总是最后一个(p4

1 个答案:

答案 0 :(得分:1)

您需要将纹理放在地图册上的不同位置。 假设您的纹理(px.png)大小为130x130:

            this.mTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 4 * 130, 130);
            this.m1TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p1.png", 0, 0);
            this.m2TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p2.png", 130, 0);
            this.m3TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p3.png", 260, 0);
            this.m4TextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p4.png", 390, 0);
            this.mTextureAtlas.load();

更好的解决方案:

int textureCount = 4;
TextureRegion[] mTextureRegions = new TextureRegion[textureCount];

for (int i = 0; i < mTextureRegions.length; i++)
   this.mTextureRegions[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTextureAtlas, this, "p" + (i + 1) + ".png", i * 130, 0);
this.mTextureAtlas.load();