Rotating an image gradually from one degree to another
This is my first post, so please bear with me. I'll try and be as clear as I can here about my problem. First off, let me say that I suck at math. I failed it in school, and it pains me to no end that I can't grasp simple math concepts, especially since I love to code. Someone who wants to program, and can't perform basic math operations? Bad combo. Aaaanyway, on to the problem.
Some context. I am writing an asteroids-type game. It's coming along quite nicely, and I've overcome all my hurdles so far thanks to this site (thank you!), and google. I've searched high and low to a solution to my problem, but it always seems like I run into a solution that either doesn't work, or I just don't understand and can't incorporate it into my code.
The issue involves rotation of the ship. I have an onscreen joystick class that returns the angle that the joystick is being pushed. I use that angle to point the ship in that same direction.
What I want to do is gradually turn the ship towards the angle the user wants to go, using the shortest turn, left or right. In my mind I'm开发者_运维百科 thinking "How the hell do I go to say.. 350 degrees from 5 degrees, going left?". I don't know...
Here is my draw code:
public void draw(Canvas canvas){
canvas.save();
canvas.rotate((float) (fAngle + 90), (float) (dX + (mShip.getIntrinsicWidth() / 2)), (float) (dY + (mShip.getIntrinsicHeight() / 2)));
mShip.setBounds((int)dX, (int)dY, (int)dX + mShip.getIntrinsicWidth(), (int)dY + mShip.getIntrinsicHeight());
mShip.draw(canvas);
canvas.restore();
}
The angle is passed to the fAngle variable from the joystick getangle method. The angle is then increased by 90 degrees because of the image facing.
user.fAngle = oJoystick.getAngle();
So on each game tick, I want to turn the ship towards whatever direction the player wants to go, degree by degree. Any help with this would be greatly appreciated!
Thanks for reading!
In your tick function, instead of: user.fAngle = oJoystick.getAngle();
Use this (adjust increment to your liking - this controls the rotation speed):
const float increment = 1.0;
float direction;
float joy = oJoystick.getAngle();
float ang = user.fAngle;
float fudge = 5.0;
if (abs (joy - ang) > fudge) {
if (joy > ang) {
if (joy - ang < 180)
direction = 1;
else
direction = -1;
} else if (joy < ang) {
if (ang - joy < 180)
direction = -1;
else
direction = 1;
}
} else // already pointing right direction
direction = 0;
user.fAngle = ang + direction * increment;
if (0 > user.fAngle)
user.fAngle += 360;
if (360 < user.fAngle)
user.fAngle -= 360;
精彩评论