0

我正在教自己制作一个类似于“小行星”的 2D 射击游戏,换句话说:按左右键将使船转向,按向前将使船朝转向的方向移动。

我设法让船回到它所面对的方向,但偏向一边。

船舶运动的代码相当简单,希望解决方案同样简单。

我究竟做错了什么?船为什么要横着走?干杯。

float velocity = 5f;

double angle = 0;

Vector2 trajectory = new Vector2(velocity) * new Vector2((float)Math.Cos((double)angle,(float)Math.Sin((double)angle));

if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            location += trajectory;   
        }
4

2 回答 2

2

鉴于您显示的代码,没有太多要继续的事情,但我会调查两件事。

首先,您的计算可能没问题,但您可能正在横向绘制船。

其次,您的三角计算可能会被交换。由于正弦和余弦是彼此 90 度的相移,因此将它们弄错方向很可能会表现为横向移动。您需要确保您的计算与您的坐标系相匹配。

不是真正的确定性解决方案,更多的是要检查的一些事情,但正如所解释的,如果您提供更多详细信息,您可能会得到更好的答案。

于 2013-06-08T22:04:51.860 回答
0

Take a look at the wikipedia article for cartesian coordinates. And also Troigonometric functions (particularly the bits about unit circles).

To get a vector for an angle you use (as you have in your post) x = cos(angle) and y = sin(angle) (and don't forget that these methods take angles in radians, not degrees).

If you input an angle of 0 into that formula, you will have a trajectory that is traveling along the X axis. I'm guessing that your space-ship image is facing upwards? Hence the sideways movement.

The solution, of course, is to make your sprite point towards 0 degrees (ie: make it face right). Or, if you don't want to modify the image, add a fixed 90 degree offset to your angle before rotating, to compensate.

It gets a little more complicated than that - because XNA's SpriteBatch uses a client (not cartesian) coordinate system, where the Y axis is flipped (Y+ goes down, not up). So the rotation formula stays the same, it is still mathematically correct. But you might need to swap whether the left/right key increases/decreases your angle (because the Y axis is flipped, the meaning of angles also gets flipped).

于 2013-06-09T08:41:30.910 回答