Distance moved by Accelerometer

后端 未结 3 1193
故里飘歌
故里飘歌 2020-11-27 14:51

I want to move objects on iPhone screen (rectangle, circle and so on) by moving iPhone. For example, I move iPhone along X-axis and the object moves along X-axis. The same

3条回答
  •  情话喂你
    2020-11-27 15:12

    Not easy to do accurately. An accelerometer only reports acceleration, not movement. You can try (numerically) integrating the acceleration over time, but you're likely to end up with cumulative errors adding up and leading to unintended motion.

    Pseudocode, obviously untested:

    init:
        loc = {0, 0, 0}    ; location of object on screen
        vel = {0, 0, 0}    ; velocity of object on screen
        t = 0              ; last time measured
    
    step:
        t0 = time          ; get amount of time since last measurement
        dt = t0 - t
        accel = readAccelerometer()
        vel += accel * dt  ; update velocity
        loc += vel * dt    ; update position
        displayObjectAt(loc)
    

提交回复
热议问题