我想在java中旋转一个Image,用
初始化 playerimage = Toolkit.getDefaultToolkit().getImage("C:/Game/player.png"); //Load Player Image
绘制:
Graphics2D g = buffer.createGraphics();
g.drawImage(playerimage, player.getX(), player.getY(), null); // Draw Player
现在,我想要我的playerimage,旋转到我的鼠标,所以它基本上看我的鼠标。我该怎么做?
答案 0 :(得分:1)
您需要做的第一件事就是将鼠标位置和播放器位置放在同一个坐标系中。当你获得我们的鼠标位置时,它通常会在屏幕坐标中,而你的播放器可能在你自己的“世界坐标”空间。如果玩家位置直接与像素相关联,那么您可以跳过。
将鼠标位置转换为世界坐标..
mouseWorld.X = (mouseScreen.X / screenWidth) * worldWidth;
一旦进入相同的坐标系,您需要找到旋转所需的角度。此等式将根据您的播放器艺术面向哪种方式而改变,假设它面向X轴位置。然后你可以使用点积来找到你的玩家面对的位置和点指向的位置之间的角度。
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
让我们做代码......
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);
然后调用'rotate'并传入angBetween!
仔细检查单位是否正确,通常acos将返回'弧度',旋转功能将采用'度',因此您需要转换。
更多矢量信息: Vector Info