Forum Archive

"scene.gravity" and orientation

Sebastian

I'm still kinda wondering about the scene.gravity. I mentioned something about it here. How can I get the scene.gracity to follow my device's orientation?

dgelessus

scene.gravity is deprecated - you should use motion.get_gravity instead, which is independent of the scene module.

Basic usage looks like this:

import motion

motion.start_updates()
print(motion.get_gravity())
motion.stop_updates()

All code that makes use of motion data needs to go between start_updates and stop_updates. If the code inside might raise an exception, you should put the entire thing in a try-finally block to make sure that motion updates are stopped so your battery doesn't drain too quickly.

import motion

motion.start_updates()
try:
    pass # Do motion things
finally:
    motion.stop_updates()

The try block will not catch any exceptions, it only ensures that the finally block is run whether an exception is raised or not.

Sebastian

I'm having the same issues with the motion module as well...

I'm relying on the accelerometer to move around in my game, and I need to get the motion.get_gravity relative to the device orientation.

omz

You will have to convert the values yourself. It shouldn't be that hard, if I'm not mistaken – you'd just have to swap the x and y coordinates.

Sebastian

That's what I've been doing right now. Thanks for the answers guys!
Using the following code, I managed to see which orientation is being used.

# coding: utf-8

import scene
import motion


class MyScene (scene.Scene):
    def setup(self):
        self.label_node = scene.LabelNode('', ('Arial', 12), position=self.size*0.5, parent=self)
        motion.start_updates()
        self.orientation = '?'


    def update(self):
        x, y, z = motion.get_gravity()
        if abs(x) > abs(y):
            if x > 0:
                self.label_node.text = 'LANDSCAPE, RIGHT'
            else:
                self.label_node.text = 'LANDSCAPE, LEFT'
        else:
            if y < 0:
                self.label_node.text = 'PORTRAIT'

    def did_change_size(self):
        self.label_node.position = self.size*0.5

    def stop(self):
        motion.stop_updates()

scene.run(MyScene())