Creating a slow motion effect with Corona SDK

After reading through Corona’s forums, I was inspired to create this post. If you haven’t visited it yet, I would recommend taking a look. There are some great questions and answers on there!

With Corona SDK, you can use physics to do all sorts of fun things – use gravity, detect collisions, and for the purposes of this thread post, slow down physics based items. There are plenty of ways to achieve a slow motion effect (also known as bullet-time), but using the physics library makes it super easy.

We’ll start off by requiring in the physics library, creating a ball object, and attaching a physics body to the ball object.

local physics = require( "physics" )
physics.start()

local ball = display.newCircle(0,0,10)
ball.x = 100
ball.y = 10
physics.addBody(ball)

When you run this piece of code, you’ll see a ball dropping from the top of the screen to the bottom of the screen. The ball will gather speed as it drops down towards the bottom of the screen due to gravity. We can slow the drop by setting our time step to a different value.

The time step is in seconds and refers to the time between each physics cycle. We can achieve this by using physics.setTimeStep(1/120) or physics.setTimeStep(1/60). The former will update 120 per second and the latter will update 60 per second.

Your new set of code will look like this:

local physics = require( "physics" )
physics.start()

local ball = display.newCircle(0,0,10)
ball.x = 100
ball.y = 10
physics.addBody(ball)

physics.setTimeStep( 1/120 )

This is a great and simple approach if you want to slow the game down from the very beginning. However, what if you wanted to slow the game down while the game is active or while the ball is dropping? You would start by calling physics.setTimeStep(1/120) and then later on, you would reset the time step by calling physics.setTimeStep(-1).

In the code below, I’m using anonymous timer functions to call the time steps, but you could call it with the touch of a button.

local physics = require( "physics" )
physics.start()

local ball = display.newCircle(0,0,10)
ball.x = 100
ball.y = 10
physics.addBody(ball)

timer.performWithDelay(1000, function()
 physics.setTimeStep( 1/120 )

 timer.performWithDelay(1000, function()
  physics.setTimeStep(-1)
 end, 1)

end, 1)

And with that, you’ve got your very own slow down effect using Corona SDK! If you have questions or comments, please let me know below. Thanks for reading!

Daniel Williams

Leave a Reply

Your email address will not be published. Required fields are marked *