here’s some drag and drop annotated code you can play with. It does everything you asked for.
If you don’t understand something, just ask.
[code]
physics = require(“physics”) – we need the physics model
physics.start()
physics.setGravity(0,9.8)
local _H = display.contentHeight; --cache the height of the screen
local _W = display.contentWidth; – cache the width of the screen
local canJump = false --controls when jumping is allowed, initially the ball is in the air. We will set this to true when the ball collides with the ground.
local ground = display.newRect(0,0,_W,5) – rectangle is the width of the screen.
ground.x = _W/2
ground.y = _H - ground.contentHeight/2
ground:setFillColor(0,255,0) --R, G & B values respectively.
physics.addBody(ground, “static”, {friction = 2.5, bounce=0.2})
ground.myName = “ground” – assigns a name to determine which physics object collides with another.
local function spawnBall() --doesn’t have to be in a function, but you may want multiple balls. each time this function is called a new ball will spawn.
ball = display.newCircle(0,0,35) – create a ball
ball.x = _W/2 – centre of the screen on x axis
ball.y = _H/2 – centre of screen on y axis
ball:setFillColor(255,0,0) --R, G & B values respectively.
physics.addBody(ball, {friction = 2.5, bounce=0.2, radius=35 })
ball.myName = “ball” – assigns a name to determine which physics object collides with another.
end
spawnBall() – spawns a ball using the above function
local function onScreenTouch( event )
if event.phase == “began” then
if canJump == true then
– make ball jump
ball:applyForce( 0, -15, ball.x, ball.y )
end
canJump = false
end
return true
end
Runtime:addEventListener( “touch”, onScreenTouch )
function stopMovementOffSides() – *** this will stop the ball going off the sides, though it doesn’t work here as it doesn’t move and right!
if ball.x < 0 then
ball.x = 0
end
if ball.x > _W then
ball.x = _W
end
end
Runtime:addEventListener(“enterFrame”, stopMovementOffSides ) – this calls the named function every frame, (30 times per second)
function onLocalCollision( self, event ) – function to work out local collisions.
if ( event.phase == “began” ) then
if (self.myName == “ball” and event.other.myName == “ground”) then
canJump = true – *** when the ball hits the ground, we say he can jump ***
end
print( self.myName … ": collision began with " … event.other.myName )
end
end
ball.collision = onLocalCollision
ball:addEventListener( “collision”, ball )
[/code] [import]uid: 67933 topic_id: 23314 reply_id: 95241[/import]