1
在我的遊戲中,我有一個圓形陣列,它形成一個圓形邊界,在邊界內我有一個應該彈跳的球,我希望球彈起任何邊界圈。問題在於球沒有彈跳,它只是通過了。這裏是我的代碼:用LibGDX彈出另一個圈的圓圈
private Array<Circle> colCircles = new Array<Circle>(); // circle array
// method to calculate circle position
private Vector2 calculatePosition(int i) {
float cx = Constants.CENTER_X;
float cy = Constants.CENTER_Y;
float angle = 4 * i;
float x = (float) (cx + m * Math.cos(Math.toRadians(angle)));
float y = (float) (cy + m * Math.sin(Math.toRadians(angle)));
return new Vector2(x, y);
}
然後,我創建的圈子是這樣的:
for (int i = 0; i < 90; i++) {
Vector2 pos = new Vector2(calculatePosition(i));
Circle c = new Circle(pos, colRadius);
colCircles.add(c);
Vector2 pos1 = new Vector2(calculateExPosition(i));
Circle c1 = new Circle(pos1, colRadius);
exCircles.add(c1);
}
我的球的更新方法是這樣的:
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);
}
碰撞時球之間發生,任何圈子我使用此代碼嘗試和反彈,但沒有反彈幫助!:
public void bouncer(Ball b){
// 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);
}