Why is my box2d body lopsided?
Posted: Tue Mar 27, 2018 10:15 pm
I'm using a number of libraries which may complicate the issue a bit, but essentially I've noticed that applying thrust in the direction of my Body results in it turning anticlockwise. Even if I disable gravity this occurs, and although it happens less at low gravity and at high angular damping, it is still a problem.
I create the body like this, which is using https://github.com/SSYGEN/windfield. Essentially the collider is "a composition of a single body, fixture and shape".
If I remove the joint lines above then pressing up has the desired effect of moving the body in the direction it is facing (rotation by 90 degrees so the direction it is facing is the same as visually) without causing an rotation.
This makes me think the welds are causing the center of mass to be off centre, but visually they appear correct?
I create the body like this, which is using https://github.com/SSYGEN/windfield. Essentially the collider is "a composition of a single body, fixture and shape".
Code: Select all
function factory.ship(gameState, x, y, size, callback)
local world = gameState.physics.world
-- create a triangle
local shipBody = world:newPolygonCollider(
{-size,-(2*size/3), 0,size, size,-(2*size/3)}
)
shipBody:setPosition(x, y)
local weaponWidth = size*0.2
-- place each weapon on each side of the ship
shipWeapon1 = world:newRectangleCollider(
x - size/2 - weaponWidth/2,
-size/3,
weaponWidth,
size*1.2)
shipWeapon2 = world:newRectangleCollider(
x + size/2 - weaponWidth/2,
-size/3,
weaponWidth,
size*1.2)
-- place joint in centre of player, the weapons and the main
-- body should collide with each other
world:addJoint('WeldJoint', shipWeapon1, shipBody, x, y, true)
world:addJoint('WeldJoint', shipWeapon2, shipBody, x, y, true)
-- make collisions inellastic
shipBody:setRestitution(0.2)
shipWeapon1:setRestitution(0.2)
shipWeapon2:setRestitution(0.2)
-- minimise unwanted spinning, especially on welded weapons
shipBody:setAngularDamping(20)
shipWeapon1:setAngularDamping(20)
shipWeapon2:setAngularDamping(20)
-- make movement slow down
shipBody:setLinearDamping(0.1)
shipWeapon1:setLinearDamping(0.1)
shipWeapon2:setLinearDamping(0.1)
...
Code: Select all
if gameState.inputs.up.down then
local angle = player:getAngle() + math.pi/2
local dx, dy = 50*math.cos(angle), 50*math.sin(angle)
player:applyLinearImpulse(dx, dy)
end