简体   繁体   中英

Bounce a circle of another circle with LibGDX

In my game i have an array of circles that form a circular boundary, inside the the boundary i have a ball that is supposed to bounce around, I want the ball to bounce off any of the boundary circles. The problem is that the ball is not bouncing, it's just passing right through. Here is my code:

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);
}

Then i create the circles like this:

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);

    }

The update method for my ball is this:

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);
}

when collision happens between the ball and any of the circles i use this code to try and bounce but there is no bounce help!:

 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);
}

In update() method, Your velocity is calculated by direction vector and speed quantity.

so change direction instead of velocity.

 direction.rotate(180);   // for centric bounce

other wise if you want some deviation, calculate angle between mid center and ball position and use some random deviation.

direction.setAngle(angle-180+ MathUtils.random(-18,18));
direction.nor(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM