XNA вектор математическое движение
Я делаю 2D ролевую игру сверху вниз в C# xna для своего класса игрового дизайна в колледже. Я пытаюсь создать простой ИИ, который перемещает противника к игроку. в настоящее время мой код следующий
/// <summary>
/// method to move the enemy
/// </summary>
/// <param name="target">the position of the target</param>
/// <returns>the new position to be moved to</returns>
public virtual Vector2 move(Vector2 target)
{
Vector2 temp = (target - Position); // gets the difference between the target and position
temp.Normalize(); // sets the vector to unit vector
temp *= moveSpeed; // sets the vector to be the length of moveSpeed
float x = temp.X;
float y = temp.Y;
float xP, yP;
double angle = Math.Acos(((x * direction.X) + (y * direction.Y)) / (temp.Length() * direction.Length())); //dot product finds the angle between temp and direction
angle *= agility; //gets the angle to move based on agility
xP = (float)(Math.Cos(angle) * (x - direction.X) - Math.Sin(angle) * (y - direction.Y) + x);
yP = (float)(Math.Sin(angle) * (x - direction.X) - Math.Cos(angle) * (y - direction.Y) + y); // these lines rotate the point x,y around the direction vector by angle "angle"
return new Vector2(xP, yP);
}
цель передается правильно в методе обновления:
/// <summary>
/// updates the enemy
/// </summary>
public void update()
{
this.Position = move(Game1.player.Position);
}
но враг не двигается вообще. Я добавил код в конструктор, чтобы убедиться, что ловкость и скорость перемещения не равны 0. Изменение этих значений ничего не дает.
Спасибо за любую помощь.
1 ответ
В вашем коде вы возвращаете это (код для угла направления):
xP = (float)(Math.Cos(angle) * (x - direction.X) - Math.Sin(angle) * (y - direction.Y) + x);
yP = (float)(Math.Sin(angle) * (x - direction.X) - Math.Cos(angle) * (y - direction.Y) + y); // these lines rotate the point x,y around the direction vector by angle "angle"
return new Vector2(xP, yP);
Но вам нужно вернуть это для хода:
temp *= moveSpeed; // sets the vector to be the length of moveSpeed
float x = temp.X;
float y = temp.Y;
...
return new Vector2(x, y);