开发者

android: moving shape/image with values from accelerometer

开发者 https://www.devze.com 2023-02-04 09:08 出处:网络
ive managed to get out the accelerometers values (x,y,z). Is there an easy way to make a circl开发者_如何学Ce move with those values? I would also like it to stop at the edges of the screen. Thanks!I

ive managed to get out the accelerometers values (x,y,z). Is there an easy way to make a circl开发者_如何学Ce move with those values? I would also like it to stop at the edges of the screen. Thanks!


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消