How to Rotate an Object Using Touch

In order to create unique games with Corona SDK, you’ll run across different scenarios where you need a bit of math. Whether it’s spinning a prize wheel, selecting some type of navigation, or just spinning things for fun, you may need to rotate an object in your next game.

In this post, you’ll learn how to use some math to rotate an object based on the location of a player’s touch. Since there’s only 33 lines to make this code happen, and less if you take out the line breaks and background, I’ve decided to leave comments next to each code block below. However, at a high level overview, the code rotates an object that’s on the center of the screen. The rotation is based on the player touch and the object rotates around accordingly. I use math.pi and math.atan2 to help calculate the rotation for the object.

-- Create a variable to store the number that will be used for circle adjustment
local adjustment = 0

-- Add a simple background
local background = display.newRect(0,0,display.actualContentWidth, display.actualContentHeight)
background.x, background.y = display.contentCenterX, display.contentCenterY

-- Add the spin wheel
local spinWheel = display.newImageRect( "circle.png", 250, 250 )
spinWheel.x, spinWheel.y = display.contentCenterX, display.contentCenterY

local function onTouch(event)
-- Set the focus on the spin wheel
display.getCurrentStage():setFocus( )

-- In the began phase, capture some original locations and calculate the original adjustment.
if(event.phase == "began") then
local dx = event.x - (spinWheel.x)
local dy = event.y - (spinWheel.y)
adjustment = math.atan2(dy,dx) * 180 / math.pi - spinWheel.rotation

-- In the moved phase, the player is dragging their finger or stylus around the screen. We'll grab the new event location and rotate the spin wheel accordingly.
elseif(event.phase == "moved") then
local dx = event.x - spinWheel.x
local dy = event.y - spinWheel.y
spinWheel.rotation = (math.atan2(dy,dx) * 180 / math.pi) - adjustment



-- Turn on the event listener!
spinWheel:addEventListener('touch', onTouch)

This tutorial is based on a code gem from user scottrule44 in the Corona blog forums. He answered a question and I felt like this code should be seen! If you have any questions or comments (or if you are scottrule44, I’m happy to link to your site), leave them below!

Leave a Reply

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