开发者

Rotate a Image to MousePos?

I want to rotate an Image in java, initialized with

            playerimage =开发者_如何学编程 Toolkit.getDefaultToolkit().getImage("C:/Game/player.png"); //Load Player Image

drawed with:

        Graphics2D g = buffer.createGraphics();
    g.drawImage(playerimage, player.getX(), player.getY(), null); // Draw Player

Now, I want my playerimage, to rotate to my mouse, so it's basically looking to my mouse. How would I do this?


The first thing you'll need to do is get both the mouse pos and the player pos in the same coord system. When you get our mouse pos it will normally be in Screen Coords while your player maybe in your own 'World Coords' space. If the players position is tied directly to pixels then you can skip ahead.

Convert the Mouse Position to World coords..

mouseWorld.X = (mouseScreen.X / screenWidth) * worldWidth;

Once you are in the same coord system you need to find the angle required to rotate. This equation will change based on which way your Player art is facing, lets assume it is facing up the position X axis. Then you can just use the dot product to find the angle between where your player is facing and where the point is pointing.

The dot product is A(dot)B = mag(A) * mag(B) * cos (theta) 
mag = magnitude of the vector
theta = angle between the two vectors
So if you normalize the vectors (make them length 1) then..
A(dot)B = 1 * 1 * cos(theta)
A(dot)B = cos(theta)
acos(A(dot)B) = theta

So lets do code...

Vector mouseVec(mouseWorld.X, mouseWorld.Y);
Vector playerVec(playerWorld.X, playerWorld.Y);

//You want to find the angle the player must turn, so pretend the player pos it the origin
mouseVec -= playerVec;

//Create a vector that represents which way your player art is facing
Vector facingVec(1, 0);

mouseVec.Normalize();  //Make their length 1
facingVec.Normalize();

double dotProd = mouseVec.dot(facing);
double angBetween = acos(dotProd);

then call 'rotate' and pass in the angBetween!

Double check that the units are correct, often acos will return 'radians' and the rotate function will take 'degrees' so you need to convert.

More vector info: Vector Info

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜