Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm attempting to play with graphics using Java/Slick 2d. I'm trying to get my sprite to rotate to wherever the mouse is on the screen and then move accordingly. I figured the best way to do this was to keep track of the angle the sprite is at since I have to multiply the cosine/sine of the angle by the move speed in order to get the sprite to go "forwards" even if it is, say, facing 45 degrees in quadrant 3. However, before I even worry about that, I'm having trouble even getting my sprite to rotate in the first place. Preliminary console tests showed that this code worked, but when applied to the sprite, it just kind twitches. Anyone know what's wrong?

int mX = Mouse.getX();
    int mY = HEIGHT - Mouse.getY();
    int pX = sprite.x;
    int pY = sprite.y;
    int tempY, tempX;
    double mAng, pAng = sprite.angle;
    double angRotate=0;

    if(mX!=pX){
        tempY=pY-mY;
        tempX=mX-pX;

        mAng = Math.toDegrees(Math.atan2(Math.abs((tempY)),Math.abs((tempX))));
        if(mAng==0 && mX<=pX)
            mAng=180;
    }
    else{
        if(mY>pY)
            mAng=270;
        else
            mAng=90;
    }

    //Calculations
    if(mX<pX&&mY<pY){ //If in Q2
        mAng = 180-mAng;
    }
    if(mX<pX&&mY>pY){ //If in Q3
        mAng = 180+mAng;
    }
    if(mX>pX&&mY>pY){ //If in Q4
        mAng = 360-mAng;
    }

    angRotate = mAng-pAng;
    sprite.angle = mAng;

    sprite.image.setRotation((float)angRotate);
share|improve this question
add comment

closed as too localized by Byte56, John McDonald, Jonathan Hobbs, akled, Josh Petrie Oct 4 '12 at 16:03

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 1 down vote accepted

In your last statements, you're calculating the angle difference then calling setRotation.

angRotate = mAng-pAng;
sprite.angle = mAng;

sprite.image.setRotation((float)angRotate);

setRotation as the name indicates: Sets the rotation. You should replace the above with:

sprite.angle = mAng;

sprite.image.setRotation((float)sprite.angle);
share|improve this answer
add comment

Not sure if this is actually causing your issue, but you shouldn't have to abs the arguments of atan2. That will also get rid of most of the rest of this code as well.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.