0

I'm writing a simple tilting game. Make a ball roll over the screen in the direction you tilt your phone.

So I downloaded an example on how to get the sensor data and that works fine (I use a rotation matrix to avoid the Euler angle problem). But then I tried to put it into a bigger app and I have some trouble getting it to work.

My first idea was to run the tilt sensor in a separate thread but my class: public class TiltSensor extends Thread implements SensorEventListener is not working to well. I get one round of values then it stops.

How would you implement this app?

I don't want to block the UI thread so I'm thinking I need a separate thread (GameHandler) to run the game and then I call runOnUithread and from there invalidate the View. I'd also separate the board representation from the View so I'd represent the screen as a matrix and then the view would use that matrix to know how the screen should look. But I am unsure what the best way to implement the TiltSensor. Should it run in a separate thread or the same thread as the GameHandler? How do I make sure the SensorManager actually calls the onSensorChanged in the GameHandler thread?

1 Answers1

1

In my humble experience, you should:

A) Register your SensorListener on your main thread normally, but make it spawn two (or as needed) WorkerThreads on its constructor.

B) Get the looper reference of both threads, to keep them alive waiting for future requests.

B) Listen to your onSensorChanged on your main thread normally, but do NOTHING OTHER (this is important) then delegate a copy of the values to a new runnable object that will process your game logic.

C) Enqueue your new runnable object on your WorkerThread looper reference accordingly.

D) Make the runnables (that are already off your main thread) do what they have to do and synchronize changes to a singleton that may be consulted by who is interested in updating your views.

reis_eliel
  • 338
  • 2
  • 7