2013-11-26 26 views
0

我想使對象滑過鼠標,每次它被點擊。它會不斷移動。現在,如果我點擊它的前面(上方或下方),它會朝大體方向移動,但角度不對。當我點擊後面時,它會減慢很多,最接近它的速度非常緩慢。如何使對象「飛」到鼠標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; 
+0

你爲什麼使用cos/sin?他們在這方面對我來說沒有意義。 – lukegravitt

+0

我需要找到從鼠標創建的假想三角形的角度和對象的位置,找出多少「x」和多少「y」來添加。 – user2939446

回答

3

如果PaullocationVector2你可以簡單地計算出它的位置和你用鼠標點擊座標之間的差異,那麼就歸你會得到方向可循。

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

Paullocation += direction * speed; 
+0

哇。這很簡單,謝謝! – user2939446

+0

'Vector2'結構及其方法可能非常有用,你應該看看:) – pinckerman

+0

我該如何改變它,以便一旦它擊中鼠標,它將以相同的角度反彈(如果它向東北30度,它擊中鼠標並在東南方向30度反彈)? – user2939446