2015년 9월 15일 화요일

[Guide] Floating in circular boundary (or rectangular) with accelerometer sensor

This guide is about floating, moving a point in coordinate system.

It may be useful to make spirit level (bubble level) or magic 8 ball and so on 

Just use device's accelerometer sensor to moving a center point.

I wrote android custom view which implements SensorEventListener.

Do some initialization (measuring screen size, set boundary size, assign values...) first.

Draw the x, y axis and boundary and little circle.

In end of the onDraw(), invalidate() makes little circle keep moving.



Important formula to make little circle inside circular boundary is below.



add the sensor's value to x, y coordinate (xCon, yCon) and check it is out of the circular boundary.
If it is change the value with the Formula

x = cos(atan2(y, x)) * CIRCULAR_BOUDNARY_RADIUS
y = sin(atan2(y, x)) * CIRCULAR_BOUDNARY_RADIUS

You can select the circle to float on water or roll on ground just change addition <-> subtraction.

- For simulating object floating on water, against gravity
xCon += mSensorX;
yCon -= mSensorY;

- For simulating object rolling on ground, adjust to gravity
xCon -= mSensorX;
yCon += mSensorY;

Also you can change boundary shape easily
For rectangle boundary





onSensorChanged() I just add sensor values(weighted) to center point x, y and it seems to be quite enough to do rough simulation.

Whole source code of my custom view is like below.




Hope this is helpful!

Thanks

댓글 없음:

댓글 쓰기