2012-06-11 80 views
0

我是編程新手,我正在嘗試製作一個2d小程序,它可以將鼠標移離圓圈或球。我希望這個程序中的物理學工作的方式是使物體像一個球一樣行動,而鼠標像一個可移動的小山。當鼠標靠近球時,它將球排斥得更快更遠,當鼠標離球越遠時,球慢下來並最終停止移動。我需要考慮鼠標和物體之間的總距離以及x和y距離,因此物體的移動更加平滑和逼真。我遇到的最大問題是,即使兩點之間的距離變大,球離開的速度也保持相對恆定。目前的比率是x或y的距離乘以常數,再除以總距離。當鼠標靠近物體時,這或多或少都會起作用,並且速度會隨着它的增加而增加,但當鼠標移開時它會失敗。當鼠標移開時,我希望速率降低並最終變爲0,但在我目前的設置中,隨着距離增加,x距離也會增加,並且速率不會像我想要的那樣降低,如果根本。我現在擁有的方式可能需要一起整理,並感謝您的幫助。需要幫助以正確的速度遠離鼠標移動物體

public void mouseMoved (MouseEvent e) 
{ 
    //distance between x coord 
    xd=e.getX()-x; 
    //distance between y coord 
    yd=y-e.getY(); 
    //total distance between mouse and ball 
    d=Math.sqrt((Math.pow(xd,2))+(Math.pow(yd,2))); 

    //rate of x change 
    xrate=(Math.sqrt(Math.pow(xd,2))*4)/(d); 
    //rate of y change 
    yrate=(Math.sqrt(Math.pow(yd,2))*4)/(d); 

    //determines movement of ball based on position of the mouse relative to the ball 
    if(xd>0) 
    { 
     x=x-((int)(xrate)); 
    } 
    if(xd<0) 
    { 
     x=x+((int)(xrate)); 
    } 
    if(yd>0) 
    { 
     y=y+((int)(yrate)); 
    } 
    if(yd<0) 
    { 
     y=y-((int)(yrate)); 
    } 

    //updates x and y coords of ball 
    repaint(); 
} 
+0

所以基本上就像一個排斥磁鐵? – ghostbust555

回答

0

嘗試這個 -

//rate of x change 
xrate=(1.0/(d))*20; //20 is just a random constant I guessed 
//rate of y change 
yrate=(1.0/(d))*20; 
+0

此外,你必須檢查,以確保你不會嘗試除以0 – ghostbust555

0

你只是做了錯誤的數學。

//total distance between mouse and ball 
d=Math.sqrt((Math.pow(xd,2))+(Math.pow(yd,2))); 
//rate of x change 
xrate=(Math.sqrt(Math.pow(xd,2))*4)/(d); 

想想這個:

如果你只在x線移動,只會使碼等於0和d = | XD |

所以xrate = | XD | * 4 /(d)= d * 4/d = 4

有一種簡單的方法來完成你的任務,只是讓xrate和yrate與XD和YD有關。

你可以試試這個:

if(xd==0){ 
    xd = 0.1;//minimum distance 
} 
if(yd==0){ 
    yd = 0.1; 
} 

xrate = (1/xd)*10; // you can change number 100 for proper speed 
yrate = (1/yd)*10; 
x = x - xrate; 
y = y - yrate; 

希望這可以幫助。