1

每当我有一个角色并且我希望他移动到一个对象时,我总是必须将它转换为一个角度,例如:

int adjacent = myPosition.X - thatPosition.X;
int opposite = myPosition.Y - thatPosition.Y;

double angle = Math.atan2(adjacent, opposite);

myPosition.X += Math.cos(angle);
myPosition.Y += Math.sin(angle);

是否有一种更简单的方法可以通过仅使用矢量而不是转换为角度和返回来将对象移动到另一个对象,如果是这样,如果您展示了如何和/或将我指向可以向我展示的网站,我将不胜感激。

ps 我在 XNA 中编码

4

1 回答 1

1

是的,您可以最小化三角函数并采用更线性的代数方法。看起来像这样:

//class scope fields
Vector2 myPosition, velocity, myDestination;
float speed;

//in the initialize method
myPosition = new Vector2(?, ?);
myDestination = new Vector2(?, ?);
speed = ?f;//usually refers to "units (or pixels) per second"

//in the update method to change the direction traveled by changing the destination
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
myDestination = new Vector2(?', ?');//change direction by changing destination
Velocity = Vector2.Normalize(myDestination - myPosition);
velocity *= speed;

myPosition += velocity * elapsed;

//or instead of changing destination to change velocity direction, you can simply rotate the velocity vector
velocity = Vector2.Transform(velocity, Matrix.CreateRotationZ(someAngle);
velocity.Normalize();
velocity *= speed;

myPosition += velocity * elapsed;

这里使用的唯一角度/三角是嵌入在 CreateRotationZ() 方法中的三角,它在 xna 框架的幕后发生。

于 2013-01-05T14:24:13.887 回答