Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

How do I use a device's gyroscope to manipulate a ball on a screen?

I'm making an app that will manipulate a ball by having the player tilt the screen to move the ball. Code wise how do i achieve this? How do I attach a ball (how do I make a 2D ball to be manipulated in the first place?) to the position data getting abilities of a phone's gyroscope to move the ball according to how the player tilts the screen?

THANK YOU SOOOO MUCH!!!

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Benyam;

The other alternative to the gyroscope is the accelerator sensor. There is a decent tutorial on the Tilt Ball Concept here.

Ken

Rebecca Rich
PLUS
Rebecca Rich
Courses Plus Student 8,592 Points

Here are a few things you can check out to maybe get you stared in this direction.

For drawing a 2D Ball (or circle) on the screen, you could consider just drawing the circle shape:

http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VN6KcbDF8h4

or using a circle drawable:

http://stackoverflow.com/questions/3185103/how-to-define-a-circle-shape-in-an-android-xml-drawable-file

As far as using the Android gryoscope, consider looking over the docs for the Android sensors:

http://developer.android.com/guide/topics/sensors/sensors_motion.html

or specifically about Sensor Event values for Sensor.TYPE_GYROSCOPE:

http://developer.android.com/reference/android/hardware/SensorEvent.html#values

(You might also consider Sensor.TYPE_ROTATION_VECTOR .. can help with data accuracy and offers some sensor fusion.)

Whatever you do, keep in mind that constant use of the gyroscope events could drain device batteries.

There is some useful info here on gyroscope sensitivities and trying to limit your balls movement for only significant movements of the phone, etc.:

http://stackoverflow.com/questions/20693547/when-to-use-accelerometer-or-gyroscope-on-android