Change sprite on tilt

I want to change the animation/sequence of the player when the device is tilted so I tried something like this:

[lua]

function acc:accelerometer(event)

player.x = display.contentCenterX - ((display.contentCenterX + 100) * event.yGravity)

If event.yGravity > display.contentCenterX then
 player:setSequence(“turnRight”)

 player.play()

 print(“going right”)
else
 player:setSequence(“turnLeft”)

 player.play()

print(“going right”)

 end

end[/lua]

Note that the orientation of the device is on landscape so I am checking yGravity instead of xGravity.

I do this function to check whether the yGravity is negative or positive, if negative then animate to left else go right

The ‘print’ line works when I tilt the device, however the player does not change the sprite animation. I have added sprite sheets and sequences correctly before this code.

Am I dong something wrong in the conditions? Should I not put the accelerometer listener as a local function? If you guys have any other solution or workaround for this, that would really help me!

And another question, what does yRaw/xRaw/zRaw do? I don’t seem to get what the documentation says. And last how can I check how much the device is tilted?

Thanks in advance!

Hi @phoenix_karl721,

The first thing to note is that the “yGravity” value is always in relation to portrait orientation, so you’ll need to compensate by 90 degrees in checking this value when using landscape. See the docs here:

http://docs.coronalabs.com/api/event/accelerometer/yGravity.html

Secondly, you have a syntax error with your sprites. The proper call is “sprite:play()”, not “sprite.play()”. Note the usage of the “:” versus the “.”. For reference, here’s a list of the sprite-related APIs and properties:

http://docs.coronalabs.com/api/type/SpriteObject/index.html

Take care,

Brent

Hi @phoenix_karl721,

The first thing to note is that the “yGravity” value is always in relation to portrait orientation, so you’ll need to compensate by 90 degrees in checking this value when using landscape. See the docs here:

http://docs.coronalabs.com/api/event/accelerometer/yGravity.html

Secondly, you have a syntax error with your sprites. The proper call is “sprite:play()”, not “sprite.play()”. Note the usage of the “:” versus the “.”. For reference, here’s a list of the sprite-related APIs and properties:

http://docs.coronalabs.com/api/type/SpriteObject/index.html

Take care,

Brent