I just wanted to know how I could get the speed that the UIAccelerometer
is moving in 开发者_如何学Pythonso that I know how fast to move a UIView
.
Oh boy this is a bit tricky.
The accelerometer does not give you Velocity, but as we all know this is acceleration. But you can figure it out (but its not that easy).
We need to use some simple physics calculations. Using V(now) = V(previous) + acceleration(from accelerometer)*time(seconds since you last made a reading);
In code you would need to do a few things.
- You must figure out when you are not moving. Eg leave device still for a second.
- When the device moves you know the device started at an initial Velocity of 0m/s
- Ok so lets pretend to make this real simple and we only check the accelerometer every 1 second (later on maybe do 10x a second.
- Ok, we get the first reading of 1 second and the acceleration was 2.
- So our velocity after 1 second from resting would be = 0 + 2*1 = 2 m/s
- GREAT, now another second has passed (total time passed is 2 seconds), acceleration 2.5 velocity now would be V(now) = Vpervious (2) + T(passed since previous reading) 1 * 2.5 = 2 + 1*2.5 = 4.5 m/s
Remember here that T here is time passed since last reading not total time.
If I am right (someone can correct me, the accelerometer is sending back the actual value of a in our equations). So you should be able to plug that in.
Also the accelerometer will be giving you 3 different values (x,y,z). So maybe first start with one direction then maybe y for another.
Would love to know if you got this working. John.
精彩评论