I am trying to make a cannon for a game. I have everything together but the pivot joint isn’t
completely fixed. I have a static base of the cannon and then the tube, it has
rotation limits at (-45, 45), but when I drag the tube it is able to go beyond
the limits, then when I let go is when it moves back to those limits. Also when
I shake it back and forth it wobbles, which I believe is part of the initial
problem, but is a problem on its own because I should be fixed at one
point and not move.
This is the code that I have right now:
physics = require( “physics” )
physics.start()
physics.setGravity( 0, 9.8 )
physics.setDrawMode( “hybrid” )
display.setStatusBar(display.HiddenStatusBar)
screenW = display.contentWidth
screenH = display.contentHeight
local function makeCannon()
local cannonTube = display.newImage(“resources/demo_cannon-tube.png”, 25, 38)
cannonTube.x = 250
cannonTube.y = 150
physics.addBody(cannonTube, {friction = .05, density = 4} )
cannonTube.gravityScale = 0
local cannonBase = display.newImage(“resources/demo_cannon-base.png”, 25, 38)
cannonBase.x = 250
cannonBase.y = 162
physics.addBody(cannonBase, “static”, {friction = .05} )
cannonBase.isSensor = true
local pin = physics.newJoint( “pivot”, cannonTube, cannonBase, cannonTube.x, cannonTube.y + 10)
pin.isLimitEnabled = true
pin:setRotationLimits( -45, 45 )
local function checkPress(event)
eventx = event.x
eventy = event.y
if event.phase == “began” then
touch = true
elseif event.phase == “ended” then
touch = false
end
end
local tdiffer = 0
local function move()
local cannonAngle = math.floor(180-math.atan2(cannonBase.x - cannonTube.x, cannonBase.y - cannonTube.y)*(180/math.pi))
if touch == true then
local touchAngle = math.floor(180-math.atan2(eventx - cannonTube.x, eventy - cannonTube.y)*(180/math.pi))
local differ = touchAngle - cannonAngle
if differ < -180 then
tdiffer = 360 + differ
elseif differ > 180 then
tdiffer = differ - 360
else
tdiffer = differ
end
if cannonAngle ~= touchAngle then
cannonTube.rotation = cannonTube.rotation + tdiffer / 2
end
end
end
Runtime:addEventListener(“enterFrame”, move)
Runtime:addEventListener(“touch”, checkPress)
end
makeCannon()
Thank you anyone that can help.