I thought I would post the original code from the Keep It Up game from my last post. As the game evolved I added a lot more stuff such as scaling the shadow, disorting the ball when it was kicked and including 'trick kicks' (which was a bit of a nightmare). This is the basic code as version 1. Feel free to use it and add your own twist if you wish. Simply start a new Director project, drag a ball sprite onto the Stage and position a shadow sprite one channel below it in the Score. Add a simple 'go to the frame' behaviour to the Frame and attached the ball behaviour below to the ball sprite. Done!
-- jim's bouncing ball behaviour
property my, shad
property grav, accelH, accelV
on beginsprite me
my = sprite(me.spritenum) -- sets a variable 'my' to easily refer to this sprite
grav = 1 -- the gravity, change this to change the physics of the game
accelH = 0 -- the acceleration in x direction
accelV = 0 -- the acceleration in y direction
shad = sprite(my.spritenum - 1) -- sets 'shad' to the sprite i use as a shadow
my.locv = 150 -- initial position of the ball. use (sprite(1).bottom - 20 - my.height/2) to place it on the bottom of the screen
shad.loch = my.loch -- sets the x position of the shadow to the same as the ball
end
on exitFrame me
accelV = accelV + grav -- affects gravity on the y acceleration
accelH = accelH * 0.96 -- dampens the x acceleration
my.locv = my.locv + accelV -- affects y acceleration on the balls y position
my.loch = my.loch + accelH -- affects x acceleration on the balls y position
shad.loch = my.loch -- positions the shadow to the same x location as the ball (you may like to also change the size of the shadow)
-- tells the ball what to do when it hits the left side of the screen
if my.loch < (sprite(1).left + 3 + my.width/2) then
my.loch = (sprite(1).left + 3 + my.width/2)
accelH = accelH * -0.9
end if
-- tells the ball what to do when it hits the right side of the screen
if my.loch > (sprite(1).right - 3 - my.width/2) then
my.loch = (sprite(1).right - 3 - my.width/2)
accelH = accelH * -0.9
end if
-- tells the ball what to do when it hits the top of the screen. you can add this back in if you want the ball to bounce off the top
--if my.locv < (sprite(1).top + 3 + my.height/2) then
-- my.locv = (sprite(1).top + 3 + my.height/2)
-- accelV = accelV * -0.8
--end if
-- tells the ball what to do when it hits the bottom of the screen
if my.locv > (sprite(1).bottom - 20 - my.height/2) then
my.locv = (sprite(1).bottom - 20 - my.height/2)
accelV = accelV * -0.6
end if
my.rotation = my.rotation + accelH -- rotates the ball based on the x acceleration
end
on mousedown me
-- works out the x and y accelerations when the user clicks on the ball
-- the further from the centre of the ball the harder the kick
h = (the mouseh - my.loch) * -1
v = (the mousev - my.locv) * -1
accelV = v
accelH = h
end