Hello,
I’m very new to programming and I thought I’d create a simple physics game as a fun learning project. I’ve added a spring to my game and by adapting @xxxfanta’s bouncing mushroom code I’ve figured out how to make it bounce when an object hits it and also add an impulse to the object. Here’s the problem… because it’s a spring I only want it to react when the object collides with the top.
I’ve created a complex body so the spring is made up of two rectangles with the top being a single-pixel high rectangle used as the event listener. I’ve tested the code by itself without the bouncing animation and it works fine but I can’t figure out how to combine the two.
Here is Chris’ bouncing mushroom code that I’ve adapted and added the applyLinearImpulse to:
spring.isBouncing = false
–The BounceFunction
local function bounce(obj,minScale,maxScale,time)
–Storing old scale values
local oldXScale,oldYScale = obj.xScale, obj.yScale
–Declaring default values
local minScale = minScale or 0.8
local maxScale = maxScale or 1.2
local time = time or 100
–Check if it’s already bouncing
if not obj.isBouncing then
–Set bouncing true
obj.isBouncing = true
vx, vy = ball:getLinearVelocity()
ball:applyLinearImpulse( 0, vy *(-.045), ball.x, ball.y )
–Make the bounce - you can tweak it for your own needs!
transition.to(obj,{time=time,xScale=maxScale,yScale=minScale,transition=easing.inQuad,onComplete=function()
transition.to(obj,{time=time,xScale=minScale,yScale=maxScale,transition=easing.outQuad,onComplete=function()
transition.to(obj,{time=time,xScale=oldXScale,yScale=oldYScale,onComplete=function() obj.isBouncing = false end})
end})
end})
end
end
spring:addEventListener(“collision”,function() bounce(spring,0.85,1.15,120) end)
And here is the part for the complex body:
local spring = display.newImage (“assets/graphics/spring2.png”, 220, 130)
topShape = { -15,-33, 15,-33, 15,-32, -15,-32 }
bottomShape = { -15,-32, 15,-32, 15,33, -15,33 }
physics.addBody( spring, “static”,
{ shape=topShape },
{ shape=bottomShape }
)
I tried adding if obj.selfElement == 1 in the if not obj.isBouncing then statement but that didn’t work. I tried adding another if then line after but that didn’t work either.
I would greatly appreciate any tips on how to solve this. Hopefully I’m not doing it completely wrong but maybe this is still way over my head at this point.
Mark [import]uid: 139449 topic_id: 26003 reply_id: 326003[/import]