Search code examples
androidandengine

Rotating image in Andengine


Let's suppose there are bugs coming into the screen from outside. To do this, we need to have 4 coordinates (StartX, StartY, TargetX, TargetY). How to rotate the bugs to the appropriate direction? I have been messing with this for hours and have been unable to figure out this part. So the bug comes into the screen but it is not facing the right direction. (The four coordinates are random numbers).

I am counting the gradient of the line as I learned in school:

int deltaY = TargetY - StartY;
int deltaX = TargetX - StartX;
float gradient = (float)deltaY / (float)deltaX;

Then the angle to rotate the bug:

float angle = (float) (Math.atan(gradient) * 180 / PI);

Then here is the rotation and move modifier:

registerEntityModifier(new RotationModifier(0.3f, 0, angle) {
    @Override
    protected void onModifierFinished(IEntity pItem) {
        super.onModifierFinished(pItem);

        registerEntityModifier(new MoveModifier(0.8f, StartX, TargetX, StartY, TargetY) {
            @Override
            protected void onModifierFinished(IEntity pItem) {
                super.onModifierFinished(pItem);
            }
        });
    }
});

The solution is more complex since on a line of a certain gradient the bug can come from two directions so it can face two directions. I know that a gradient of 1/2 means 26.56 degrees and in the AndEngine coordinate system it means -26.56 or -206.56 degrees depending on which side the bug comes from.


Solution

  • Try something like this:

    float bugAngle = 180 + (float) Math.toDegrees(Math.atan2((targetY - bugSprite.getRotationCenterY() - startY), (targetX - bugSprite.getRotationCenterX() - startX)));
    bugSprite.setRotation(bugAngle);
    

    Please excuse the Long Line of Death.