如何使对象“飞”到鼠标XNA

时间:2013-11-26 23:36:15

标签: c# xna trigonometry game-physics

每次点击时,我都会尝试让对象滑向鼠标。它将不断移动。现在,如果我在它前面(上方或下方)点击,它会沿着大致方向移动,但方向是错误的。当我点击它后面时,它会慢下来很多,最接近它的速度非常慢。

if (isdown()) //if the mouse is clicked
{
    double paulx = Paullocation.X + radius; //midpoints of object
    double pauly = Paullocation.Y + radius;
    double targetx = ms.X; //clicked location
    double targety = ms.Y;
    if (isdown(Keys.Space)) //if space is pressed
    {
        double hypotenuse = Math.Sqrt(Math.Pow(paulx - targetx, 2) + Math.Pow(pauly - targety, 2));
        //finds hypotenuse^
        double xcomponent = targetx - paulx; //finds both legs of triangle
        double ycomponent = targety - pauly; //that is made by mouse

        Paulincrement.X = (float)Math.Cos(xcomponent / hypotenuse); //main issue
        Paulincrement.Y = (float)Math.Sin(ycomponent / hypotenuse); //main issue

    }
}
Paullocation.X += Paulincrement.X;
Paullocation.Y += Paulincrement.Y;

1 个答案:

答案 0 :(得分:3)

如果PaullocationVector2,您可以简单地计算其位置与您用鼠标点击的坐标之间的差异,然后对其进行标准化,您将获得遵循的方向。

Vector2 direction = new Vector2(mouse.X, mouse.Y) - Paullocation;
direction.Normalize();

Paullocation += direction * speed;
相关问题