我在相对于鼠标位置的位置旋转图像时遇到了一些麻烦。我只能让图像围绕它自己的点旋转,而不是在它上面旋转。
下图说明了我想要做的事情:
这是我的代码:
Image sprite = Image.FromFile("1.png");
private Point spritePos;
public Enemy(Point Position)
{
spritePos = Position;
}
public void Render(Graphics dc)
{
dc.TranslateTransform(spritePos.X, spritePos.Y); //Sets rotation point
float angle = CalcAngle(Cursor.Position);
dc.RotateTransform(angle); //Rotates the graphics transform
dc.DrawImage(sprite, spritePos);
dc.TranslateTransform(-(spritePos.X), -(spritePos.Y));
}
private float CalcAngle(Point TargetPos)
{
Point ZeroPoint = spritePos;
if (TargetPos == ZeroPoint)
{
return 0;
}
double angle;
double hypotenuse;
//Calculates the hypotenuse using Phytagoras(a^2 + b^2 = c^2)
hypotenuse = Math.Sqrt( //hypotenuse = squared(c^2)
Math.Pow((TargetPos.Y), 2) + //a^2 +
Math.Pow((TargetPos.X), 2)); // b^2
angle = Math.Acos((TargetPos.X) / hypotenuse); //Calculates the angle in radians
angle = angle * 180 / Math.PI; //Converts the radians to degree's
//If the cursor's y position is negative('above' the player), the returned angle is also negative
if (TargetPos.Y < 0)
{
return -(float)angle;
}
else
{
return (float)angle;
}
}
一些正确方向的指示将不胜感激谢谢:)