简体   繁体   English

选择一个随机的方向和移动

[英]Choose a random Direction and Move

I want to be able to choose a random angle (between 0 and 360 or 0 and 2pi) and then have a sprite move in that direction. 我希望能够选择一个随机角度(介于0到360或0到2pi之间),然后让精灵沿该方向移动。 So far I have tried this, but it has been pretty noneffective, as it always moves down, and the angle choosing isn't very pretty. 到目前为止,我已经尝试过了,但是它一直无效,因为它总是向下移动,并且角度选择不是很好。

Random rand = new Random();

//Chooses the Angle
rotation = (float)rand.NextDouble()*MathHelper.TwoPi; 

//Is supposed to get a normalized movement vector that moves in the direction of that angle.
moveVector = Vector2.Normalize(new Vector2(-(float)Math.Tan(rotation), 1)); 

You seem to be missing a dab of trigonometry: 您似乎缺少了一点三角函数:

You're creating a vector with a Y component that's always 1 (down in 2D XNA). 您正在创建一个Y分量始终为1(在2D XNA中向下)的向量。 So, no matter the random angle, it only affects the horizontal part of the direction. 因此,无论随机角度如何,它都只会影响方向的水平部分。

To turn an angle into a (unit, ie already-normalized) directional vector, you can use sin and cos (think of the unit circle): 要将角度转换为(单位,即已经标准化的)方向向量,可以使用sin和cos(以单位圆为例):

var dir = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));

Since XNA puts the origin at the top-left of the screen for 2D, you need to reverse the y-component: 由于XNA将原点放在2D屏幕的左上方,因此您需要反转y分量:

var dir = new Vector2((float)Math.Cos(angle), -(float)Math.Sin(angle));

Additionally, to ensure you get a proper sequence of random numbers, you should only create the random object once, then use the same instance every time to get the next random number. 此外,为确保获得正确的随机数序列,您应该只创建一次随机对象,然后每次都使用相同的实例来获取下一个随机数。

Also, to get smoother motion, you can either weight the direction in favour of the direction you're already going in, or pick a random destination and travel to that (then pick another one, etc.). 另外,要获得更平滑的运动,您可以根据自己要走的方向对方向进行加权,或者选择一个随机的目的地然后前往该目的地(然后再选择一个,依此类推)。

想通了,这是正确的行:

move = new Vector2((float)Math.Cos(rotation - MathHelper.PiOver2), (float)Math.Sin(rotation - MathHelper.PiOver2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM