代码之家  ›  专栏  ›  技术社区  ›  advice

如何在love2d中设置车轮接头

  •  1
  • advice  · 技术社区  · 6 年前

    我目前正在尝试在Love2d中创建一个简单的2d汽车,但我在弄清楚如何将车轮接头连接到车身上时遇到了问题。

    https://love2d.org/wiki/love.physics.newWheelJoint

    joint = love.physics.newWheelJoint( body1, body2, x, y, ax, ay, collideConnected )
    

    要创建车轮连接,您需要传递4个数字(x,y,a x,a y),但我不知道这些值应该是什么。每次我的车撞到地上,整个东西都会吓坏并爆炸。

    正如你在下面看到的,我只是使用一个简单的 PolygonShape 和两个 CircleShapes 我想把它们附在一起。

    function Car:create()
        local object = {}
    
        local x = 300
        local y = 300
    
        local width = 120
        local height = 40
        local size = 20
    
        local hasCollision = false
    
        object.frame = Car:createFrame(x, y, width, height)
        object.frontWheel = Car:createWheel(x + width/4, y + height, size)
        object.backWheel = Car:createWheel(x - width/4, y + height, size)
    
        -- Unsure what values I should use for these.
        frontJoint = love.physics.newWheelJoint(object.frame.body, object.frontWheel.body, 400, 300, 400, 300, hasCollision)
        rearJoint = love.physics.newWheelJoint(object.frame.body, object.backWheel.body, 350, 300, 0, 0,  hasCollision)
    
        -- Trying to adjust the values to see if that helps, unsure what these should be.
        frontJoint:setSpringFrequency(1)
        frontJoint:setSpringDampingRatio(2)
    
        return object   
    end
    
    function Car:createFrame(x, y, width, height)
        local frame = {}
    
        frame.body = love.physics.newBody(world, x, y, "dynamic")
        frame.shape = love.physics.newRectangleShape(0, 0, width, height)
        frame.fixture = love.physics.newFixture(frame.body, frame.shape, 5) -- A higher density gives it more mass.
    
        return frame
    end
    
    function Car:createWheel(x, y, size)
        local wheel = {}
    
        wheel.body = love.physics.newBody(world, x, y, "dynamic") 
        wheel.shape = love.physics.newCircleShape(size) 
        wheel.fixture = love.physics.newFixture(wheel.body, wheel.shape, 1) 
        wheel.fixture:setRestitution(0.25)
    
        return wheel
    end
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   advice    6 年前

    我必须更深入地研究box2d的文档,并且能够了解哪里出了问题。我可以用下面的代码让它工作。

    function Car:createJoint(frame, wheel, motorSpeed, maxMotorTorque)
        local hasCollision = false
        local freq = 7
        local ratio = .5
    
        local hasChanged = true
    
        local yOffset = wheel:getY() - frame:getY()
    
        local joint = love.physics.newWheelJoint(frame, wheel, wheel:getX(), wheel:getY(), 0, 1, hasCollision)
        joint:setSpringFrequency(freq)
        joint:setSpringDampingRatio(ratio)
    
        joint:setMotorSpeed(motorSpeed)
        joint:setMaxMotorTorque(maxMotorTorque)
    
        return joint
    end
    

    希望这能帮助其他人寻找 newWheelJoint .