android: moving shape/image with values from accelerometer

大兔子大兔子 提交于 2019-12-08 11:03:26

问题


ive managed to get out the accelerometers values (x,y,z). Is there an easy way to make a circle move with those values? I would also like it to stop at the edges of the screen. Thanks!


回答1:


I think you can do something like this (note: partially pseudocode):

public void onSensorChanged (int sensor, float[] values) {
    //adjust someNumber to desired speed
    //values[1] can be -180 to 180
    float xChange = someNumber * values[1];
    //values[2] can be -90 to 90
    float yChange = someNumber * 2 * values[2];

    //only move object if it will stay within the bounds
    if (object.xPos + xChange > 0 && object.xPos + xChange < xBorder) {
        object.xPos += xChange;
    }
    if (object.yPos + yChange > 0 && object.yPos + yChange < yBorder) {
        object.yPos += yChange;
    }
    //force a repaint of your surface here
}

Where:

  • onSensorChanged is a method that is called each time the accelerometer moves... I'm not sure whether you are using SensorManager, but it seems convenient for your scenario. Note that you must implement this method yourself.
  • object is the circle you want to move.
  • xBorder and yBorder are the maximum bounds for the object's movement. The minimum bounds are assumed to be 0 and 0, though you can use whatever you like.


来源:https://stackoverflow.com/questions/4690208/android-moving-shape-image-with-values-from-accelerometer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!