[英]How to make an object “fly” towards the mouse XNA
我试图使对象每次单击时都向鼠标滑动。 它会不断地前进。 现在,如果我单击它的前面(上方或下方),它会沿大致方向移动,但角度错误。 当我单击它的后面时,它只会减慢很多速度,并且离它最近的移动非常缓慢。
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;
如果Paullocation
是Vector2
,则可以简单地计算其位置与您用鼠标单击的坐标之间的差,然后对其进行归一化,即可得到要遵循的方向。
Vector2 direction = new Vector2(mouse.X, mouse.Y) - Paullocation;
direction.Normalize();
Paullocation += direction * speed;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.