Search code examples
f#monogamefarseer

Farseer, MonoGame, ball does not bounce


I have successfully integrated Farseer for XNA into MonoGame with little to no trouble. Stacking, complex dynamics, etc. all seem to be working fine, but I absolutely cannot make a ball bounce on a floor. When the ball touches the ground, it simply stops there and only moves away if pushed by another ball.

My code (in F#, but it should be clear enough; <- means assignment, everything else is the same as C#) for creating the ball and the ground is:

  member physics.CreateBall(x:float32<m>,y:float32<m>,r:float32<m>,m:float32<kg>,dynamic:bool) =
    let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m> + random_range -30.0f 30.0f, y * 1.0f<1/m>) * PhysicsWorld.Scale)
    do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
    do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
    do myBody.Restitution <- 1.0f
    do myBody.Friction <- 0.0f
    do myBody.Mass <- m * 1.0f<_>
    let circleShape = new CircleShape(r * PhysicsWorld.Scale * 1.0f<1/m>, 1.0f)
    let fixture = myBody.CreateFixture(circleShape)
    { Body = myBody; Tick = Rule.Create 0 }
  member physics.CreateBox(x:float32<m>,y:float32<m>,w:float32<m>,h:float32<m>,m:float32<kg>,dynamic:bool) =
    let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m>, y * 1.0f<1/m>) * PhysicsWorld.Scale)
    do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
    do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
    do myBody.Restitution <- 1.0f
    do myBody.Friction <- 0.0f
    do myBody.Mass <- m * 1.0f<_>
    let rectangle = PolygonTools.CreateRectangle(w * PhysicsWorld.Scale * 1.0f<1/m>, h * PhysicsWorld.Scale * 1.0f<1/m>)
    let boxShape = PolygonShape(rectangle, 1.0f)
    let fixture = myBody.CreateFixture(boxShape)
    { Body = myBody; Tick = Rule.Create 0 }

Solution

  • The simplest solution of all. The code above was almost correct, minus the initialization order. Here is the working version for future reference:

    let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m>, y * 1.0f<1/m>) * PhysicsWorld.Scale)
    let rectangle = PolygonTools.CreateRectangle(w * PhysicsWorld.Scale * 1.0f<1/m>, h * PhysicsWorld.Scale * 1.0f<1/m>)
    let boxShape = PolygonShape(rectangle, 1.0f)
    let fixture = myBody.CreateFixture(boxShape)
    do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
    do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
    do myBody.Restitution <- restitution
    do myBody.Friction <- friction
    do myBody.Mass <- m * 1.0f<_>