2017-06-01 68 views
0

在我的遊戲中,我有圓形邊界,並且在邊界內有一個應該反彈的物體,但由於某種原因它不會反彈。我的代碼如下所示。如何在圓形邊界內反射對象?

public void checkBouncer(Bouncer b){ 
    float x = b.getPosition().x; 
    float y = b.getPosition().y; 
    float cx = Constants.CENTER_X - b.getWidth()/2; 
    float cy = Constants.CENTER_Y - b.getHeight()/2; 
    float dx = Math.abs(x - cx); 
    float dy = Math.abs(y - cy); 
    float r = (Constants.PARAMETER_RADIUS - 45) - b.getHeight(); 

    // check collision between bounds and bouncer 
    if ((dx * dx) + (dy * dy) >= (r * r)) { 
     // original velocity vector 
     Vector2 v1 = new Vector2(b.getVelocity().x, b.getVelocity().y); 

     // normal vector 
     Vector2 n = new Vector2(
       Constants.CENTER_X - b.getPosition().x, 
       Constants.CENTER_Y - b.getPosition().y 
     ); 

     // normalize 
     if (n.len() > 0) n = n.nor(); 

     // dot product 
     float dot = v1.x * n.x + v1.y * n.y; 

     // reflected vector values 
     v2.x = v1.x - 2 * dot * n.x; 
     v2.y = v1.y - 2 * dot * n.y; 
    } 
    // set new velocity 
    b.setVelocity(v2); 
} 

,我想反彈的目的是通過在其面對的方向移動開始時,如下所示的更新方法:

public void update(float delta) { 
    direction.x = (float) Math.cos(Math.toRadians(angle)); 
    direction.y = (float) Math.sin(Math.toRadians(angle)); 

    if (direction.len() > 0) { 
     direction = direction.nor(); 
    } 

    velocity.x = direction.x * speed; 
    velocity.y = direction.y * speed; 

    position.x += velocity.x * delta; 
    position.y += velocity.y * delta; 

    circle.set(position.x + width/2, position.y + height/2, width/2); 
} 

但是,如果我反轉碰撞它的種類的角度工作,但它是緊張的,並不總是反彈碰撞。代碼爲這裏:

if ((dx * dx) + (dy * dy) >= (r * r)) { 
     b.setAngle(-b.getAngle()); 
} 

請我需要幫助。

+0

https://stackoverflow.com/questions/28163635/bouncing-a-ball-within-a-circle – Sedrick

回答

0

電解金屬錳...你這裏反射後得到正確的速度矢量分量:

v2.x = v1.x - 2 * dot * n.x; 
and same for y 

爲什麼你需要使用的角度?

如果真正需要的方向角度出於某種原因,得到其數值爲

angle = atan2(v2.y, v2.x) 
+0

我用角度只是爲了測試碰撞是否有效,我試着用你的建議,但它不工作。 – Harry

+0

你的意思是 - 「它不工作」?錯誤的角度?錯誤的系統行爲? – MBo

+0

是在錯誤的角度彈跳,有時它是正確的。 – Harry