box2D add polygon and create polygon.

Monkey Forums/Monkey Beginners/box2D add polygon and create polygon.

Nicolas(Posted 2014) [#1]
Can you guys help me how to use add polygon and create polygon in box2D. I need some sample. Thanks


MikeHart(Posted 2014) [#2]
Here is a function you can use

	'------------------------------------------
	' Create a polygon shaped B2Body object.
	Method CreatePolygon:b2Body(vec:Float[], xpos:Float, ypos:Float, btype:Int = b2Body.b2_Body )
	'------------------------------------------
        Local shape :b2PolygonShape= New b2PolygonShape()
        Local bodyDef :b2BodyDef = New b2BodyDef()
        Local body:b2Body
        Local xp:Float
        Local yp:float
        bodyDef.type = btype
        Local vecLen:Float = vec.Length()
        Local vecLenHalf:Float = vecLen/2
       
        Local v:b2Vec2[vecLenHalf] 
        For Local vl:Int = 1 To vecLenHalf
        	v[vl-1] = New b2Vec2
        Next

        For Local i:Int = 1 To vecLen Step 2
  
			xp = vec[i-1]/m_physScale
			yp = vec[i]/m_physScale	
        	v[(i-1)/2].x = xp
        	v[(i-1)/2].y = yp
        Next
        bodyDef.position.Set( xpos/m_physScale, ypos/m_physScale)
        shape.SetAsArray(v, vecLenHalf)
        body = m_world.CreateBody(bodyDef)
        body.CreateFixture2(shape)
		Return body
	end

And call it like this:
yourBody := CreatePolygon( [ -2.5, -2.0, 2.0, 0.0, -2.2, 2.0 ], 100, 100)