如何更改精灵的位置随机出现在场景中?

时间:2011-11-07 11:55:51

标签: java android box2d andengine

我正在使用AndEngine的这个方法向屏幕添加一个精灵并让它在屏幕上移动。

 private void addFace() {
     Random rand = new Random();

        float x = (int) mCamera.getHeight() - mBallTextureRegion.getHeight();
        float minY = mBallTextureRegion.getHeight();
        float maxY = (int)(mCamera.getWidth() +  mBallTextureRegion.getWidth());
        float rangeY = maxY - minY;
        float y = rand.nextInt((int)rangeY) + minY;

     this.mFaceCount++;
     Log.e("Faces: ", "Face" + this.mFaceCount);

    Sprite face = null;
     Body body = null;


             face = new Sprite(x, y, this.mBallTextureRegion.clone());
             body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);

      this.mScene.attachChild(face);
     this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true));
             int minDuration = 2;
            int maxDuration = 4;

            int rangeDuration = maxDuration - minDuration;
            int actualDuration = rand.nextInt(rangeDuration) + minDuration;

            MoveXModifier mod = new MoveXModifier(actualDuration, face.getX(), - face.getWidth());

            face.registerEntityModifier(mod);

}

我想要做的是,不是选择随机位置而是将精灵添加到场景的左侧,我希望将它添加到顶部并倒下。

我基本上想要翻转方向, 我只是想弄清楚如何。我尝试的一切都没有运气。

有任何想法或建议吗?

1 个答案:

答案 0 :(得分:3)

虽然我对Andengine了解不多,但我怀疑你想改变这些界限:

float x = (int) mCamera.getHeight() - mBallTextureRegion.getHeight();
float y = rand.nextInt((int)rangeY) + minY;

MoveXModifier mod = new MoveXModifier(actualDuration, face.getX(), - face.getWidth());

翻转x和y语句,但如果希望它显示在屏幕外,请将y设置为-mBallTextureRegion.getHeight()。

对于MoveXModifier,我猜有相应的MoveYModifier(分别使用face.getY()和-face.getHeight())