Question

I am trying to do a volleyball game and simulating every action based on box2d. What I want to do is to have different ball restitution when player hit the ball, and ball hit the wall. So in first case ball should fly quicker, and in second case slower.

But if I am trying to set restitution for a player and for wall objects in a different way I also notice that player itself is bouncing from the wall... Is there a way I can do it in selective way? E.g. hitting floor should not cause a player to bounce.... But if player hit the ball it should bounce a lot.

Was it helpful?

Solution

Unfortunately, you're right, Box2D hasn't got this setting.

What you can do instead is listen for a contact listener event which matches both the player and the ball. When that happens you apply a very large force to the ball.

edit

I typed this off the top of my head, I'm not sure it's exactly right.

public class MyContactListener extends b2ContactListener {
    override public function Add(point:b2ContactPoint):void {
        var ball:b2Body = ...
        var player:b2Body = ... // fill these
        var force:b2Vec2;

        if(point.shape1.GetBody() == ball && point.shape2.GetBody() == player) {
            force = point.normal.Copy();
            force.Multiply(SOMETHING);
            ball.ApplyForce(force);
        } else if(point.shape1.GetBody() == player && point.shape2.GetBody() == ball) {
            force = point.normal.Copy();
            force.Multiply(-SOMETHING);
            ball.ApplyForce(force);
        }
    }
}

What's going on here.

You need to create an instance of this class and register it with the world which is probably something like world.SetContactListener(new MyContactListener) or something.

The Add() method fires when two bodies come into contact. The force applied is in the direction of the contact normal (which takes you from one body to the other).

Because of the way the contact listener system is set up, it's possible for either the ball or the player to be body #1 in the b2ContactPoint structure, so you need to code for that possibility. The direction of the normal depends on which one is body #1 (hence the minus sign). I can't actually remember which way it goes so you might need to reverse the force (put the minus sign in the other branch).

Other than that it should be reasonably clear. Box2D doesn't seem that well known here so you might have a bit more luck at the Box2D forums (http://www.box2d.org/forum/)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top