每当我有一个角色并且我希望他移动到一个物体时我总是要把它转换成一个角度,例如:
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);
是否有一种更简单的方法可以将对象移动到另一个对象,只需使用向量而不是转换为角度和背面,如果是这样的话,如果你向我展示如何和/或指向一个可以向我显示的网站,我将不胜感激。
P.S。我在XNA编码
答案 0 :(得分: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;
这里使用的唯一角度/ trig是嵌入在CreateRotationZ()方法中的trig,它是由xna框架在幕后发生的。