ByteArena / box2d

Box2D.go - Go port of Box2D - a 2D Physics Engine for Games.
Other
292 stars 48 forks source link

Nothing Moves #17

Open dragonfax opened 4 years ago

dragonfax commented 4 years ago

I followed the instructions for the hello world program, in the PDF linked from the README. And nothing moves. Perhaps I did something wrong.

func main() {

    var gravity = d2.MakeB2Vec2(0.0, -10.0)
    var world = d2.MakeB2World(gravity)

    groundBodyDef := d2.B2BodyDef{}
    groundBodyDef.Position.Set(0, -10)
    groundBody := world.CreateBody(&groundBodyDef)
    groundBox := d2.B2PolygonShape{}
    groundBox.SetAsBox(50, 10)
    groundBody.CreateFixture(&groundBox, 0)

    bodyDef := d2.B2BodyDef{}
    bodyDef.Type = d2.B2BodyType.B2_dynamicBody
    bodyDef.Position.Set(0, 4)
    body := world.CreateBody(&bodyDef)
    dynamicBox := d2.B2PolygonShape{}
    dynamicBox.SetAsBox(1, 1)
    fixtureDef := d2.B2FixtureDef{}
    fixtureDef.Shape = &dynamicBox
    fixtureDef.Density = 1
    fixtureDef.Friction = 0.3
    body.CreateFixtureFromDef(&fixtureDef)

    timeStep := 1.0 / 60.0
    velocityIterations := 6
    positionIterations := 2

    for i := 0; i < 60; i++ {
        world.Step(timeStep, velocityIterations, positionIterations)
        position := body.GetPosition()
        angle := body.GetAngle()
        fmt.Printf("%4.2f %4.2f %4.2f\n", position.X, position.Y, angle)
    }
}
$ go run main.go 
0.00 4.00 0.00
0.00 4.00 0.00
0.00 4.00 0.00
0.00 4.00 0.00
0.00 4.00 0.00
0.00 4.00 0.00
...

Truthfully I tried incorporating this module into another project I'm working on and it failed there. Which is when I took a step back, tried the hello world, and found that didn't work either.

jack-kirton commented 4 years ago

The only difference I can see between mine and yours is that instead of using B2BodyDef{} use MakeB2BodyDef(). The same applies for all the structures you have created from Box2D.

Chillance commented 4 years ago

Yes, doing bodyDef := box2d.MakeB2BodyDef() seems to output something different. It also makes sense since these "constructors" do set certain default values that wouldn't be set otherwise.

einthusan commented 3 years ago

In addition to what is said, you need to use ...

groundBox := box2d.MakeB2PolygonShape() fixtureDef := box2d.MakeB2FixtureDef() dynamicBox := box2d.MakeB2PolygonShape()

instead of using

groundBox := d2.B2PolygonShape{} fixtureDef := d2.B2FixtureDef{} dynamicBox := d2.B2PolygonShape{}

Jack3G commented 3 years ago

Just in case this helps anyone else who is looking here: The same thing was happening to me and my problem was that I had

const TIMESTEP = 1 / 60

// Instead of
const TIMESTEP = 1.0 / 60.0

If you do the first one it rounds down to 0, therefore no time passes in the simulation.