user2684521
user2684521

Reputation: 380

Moving an object using the accelerometer with Corona SDK

I am working on a small personal project to get comfortable with Corona SDK, I created a static floor and two static walls, then I create a ball and added dynamic physics to it. I made a function that moves the ball around when the accelerometer is active but I cant seem to get it right. I can make the object static and it moves around ok, but it wont interact with the dynamic walls or floor, I can make the object static but when the game loads the balls just shoots off screen and the app crashes.

Not sure how to approach this, I already looked at the sample project in corona.

Here is my code.

--Set accelerometer framerate
system.setAccelerometerInterval( 60 )
--Creates Hero
local function player(xCenter, yCenter, radius )
    local player1 = display.newImageRect( "images/hero.png", 32, 31 )
    player1.x = xCenter
    player1.y = yCenter
    player1:setFillColor( 100,100,100 )
    physics.addBody( player1, "dynamic", {bounce = 0, density=1, friction=.1, radius=radius} )
    return player1
end
local hero = player(startPlatform.x+20, startPlatform.y-15, 15)
local function heroMovex(event)
    hero.x = hero.x + (hero.x*event.xGravity)
    hero.y = hero.y + (hero.y * event.yGravity-1)
end
Runtime:addEventListener("accelerometer", heroMovex)

Upvotes: 1

Views: 893

Answers (1)

Ben Grimm
Ben Grimm

Reputation: 4371

There are a number of ways to apply the accelerometer's gravity to your physics bodies. Rather than moving the body directly by adjusting its coordinates, try setting hero's velocity to match the tilt:

local function heroMovex( event )
    hero:setLinearVelocity( 10 * event.xGravity, -10 * event.yGravity )
end

Or, if you don't mind applying the acceleration to everything, just bind gravity to the accelerometer:

local function tiltGravity( event )
    physics.setGravity( 10 * event.xGravity, -10 * event.yGravity )
end
Runtime:addEventListener("accelerometer", tiltGravity)

Upvotes: 2

Related Questions