Search code examples
c#box2dmonogamefarseer

C# Monogame & Farseer Physics: Collisions


I am a begginer. I am using Monogame and Farseer Physics Library in C#. (latest versions)

In my game, whenever my ball (circle) hits the corner of a rectangle, (or even another circle), it is supposed to only change direction on the Y-Axis.

However, it does not only change direction on the Y-Axis, (as intended), but it also moves a small amount to the right as well (or the left accordingly), depending on how you hit the corner (or another circle). It is as if some force is being put on the ball, making it move on X-Axis as well.

http://i.imgur.com/rEbNTua.png?1

This movement is cool and all, and it makes a lot of sense, but in my game, it does not, therefore i want to get rid of it.

How is this possible ? I am guessing i have to change some default values.

This what my coding looks like:

BallBody.BodyType = BodyType.Dynamic;
BlockBody.BodyType = BodyType.Static;
Ball.LinearVelocity = new Vector(0,-1); // ball going up
BallBody.OnCollision += Ball_OnCollision;

public bool Ball_OnCollision(Fixture f1, Fixture f2, Contact contact)
{
    // if the Ball (f1), collides with the Block (f2)
    if (f2.Body == BlockBody)
    // change the direction of the Ball on Y-Axis
    Ball.LinearVelocity = new Vector(0,-1);
    return true;
}

Also with high speeds, this occurs:

enter image description here

Even though the ball is never able to pass through the Block (tunneling), I want to know how could i possible fix that so that the ball never enters the Block area ?


Solution

  • Unfortunately, this is surprisingly difficult to do with Box2D. The best I could manage when I tried, was to record the velocity of the ball when the contact started, and then when the contact ends, manually set the velocity to what I wanted. That works fine when the ball only begins and end contact with one block at a time, but in some cases the ball can begin touching two blocks in the same time step. You would have to look at the arrangement of the blocks it touched, and calculate for yourself what angle you would expect it to bounce away at. Eventually I just gave up and did not bother to cover that case.