同时处理平移和旋转转换时遇到问题。我刚刚开始尝试构建小行星,这是我第一次编写 WPF 应用程序。
我的玩家飞船由 Polygon 对象表示,它对 keydown 事件执行旋转和平移。
我的旋转变换按预期单独工作。主要问题是,一旦我平移然后尝试再次旋转,旋转变换会尝试围绕前一个点旋转,即使它指定获取新的 centerX 和 centerY 坐标。
平移变换似乎使多边形大致移动了 +50x 和 +50y(即使变换中使用的坐标证明不是这样),然后它正确地沿旋转指定的方向移动。
预先感谢有人可以给我的任何帮助!
这是我的 C#:
public void handleRotate(KeyEventArgs e)
{
if (e.Key == Key.Right)
{
this.rotate(10);
}
if (e.Key == Key.Left)
{
this.rotate(-10);
}
}
public void handleUpDown(KeyEventArgs e)
{
if (e.Key == Key.Up)
{
this.move();
}
}
public double convertToRadians(double angle)
{
return (Math.PI / 180) * (angle - 90);
}
public void move()
{
double radians = convertToRadians(playerShip.getHeading());
double xMovement = Math.Cos(radians) * 10;
double yMovement = Math.Sin(radians) * 10;
playerShip.setShipCenterX(xMovement += playerShip.getShipCenterX());
playerShip.setShipCenterY(yMovement += playerShip.getShipCenterY());
MessageBox.Show("Heading: " + playerShip.getHeading().ToString() + " centerx: " + playerShip.getShipCenterX().ToString() + " centery: " + playerShip.getShipCenterY().ToString());
TranslateTransform translate = new TranslateTransform(xMovement, yMovement);
theShipShape.RenderTransform = translate;
}
public void rotate(double rotation)
{
double newHeading = playerShip.getHeading() + rotation;
RotateTransform rotate = new RotateTransform(newHeading, playerShip.getShipCenterX(), playerShip.getShipCenterY());
MessageBox.Show("Heading: " + newHeading.ToString() + " centerx: " + playerShip.getShipCenterX().ToString() + " centery: " + playerShip.getShipCenterY().ToString());
theShipShape.RenderTransform = rotate;
playerShip.setHeading(newHeading);
}
}
这是我的 xaml:
<Window x:Name="GameWindow" x:Class="AsteroidsAttempt2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas x:Name="GameCanvas" Focusable="True" IsEnabled="True" HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="517" KeyDown="GameCanvas_KeyDown"/>
</Window>