2
votes

my app contains an object moving on a surfaceview. I am able to move it around via accelerometer. Here's the movement code of the player object:

if(x + mx*speed > 0 && x + mx*speed < GameView.WIDTH) {
        x += mx*speed;
    }
if(y+ my*speed > 0 && y+ my*speed < GameView.HEIGHT) {
        y+=my*speed;
    }

x and y are the player's coordinates

mx is the value the player gets from the accelerometer, for example: when tilting to the left, mx is -2, when tilting more, mx is -4, -5, -6 etc. --> my is the same for the y-axis

the speed is a variable to modify and play around when i want to have a faster movement.

as you can see I tried to limit the movement to only move when the player is inside of the view.

Now my problem is: when tilting the device intensively to the right, mx turns to something like 6. speed is set to 5. This means, when the player's position + 6 * 5 is bigger than the game view it should not move any more. But this results in the player stopping pixels in front of the right side of the view... when tilting lightly to the right, the object stops perfectly at the border of the view...

Now how should i change the code to achieve an object that stops it's movement perfectly at borders of the screen?

Image with intensively use of accelerometer

On this picture you can see the circle not stopping quite at the bottom, as there are some pixels between the circle and the bottom border. when going slightly back with the accelerometer, the circle aligns itself to the bottom of the screen:

bottom of the screen

But now, i can only reach the screen borders when moving slowly, which means with a low mx or my.

the screenshots you can see the mY values. On the first picture my = ca. 8 and on the second ca. 6.

Any ideas?

Thanks in advance

1
A screen shot or two might help clarify your question. - D-Dᴙum
added two screenshots - user2410644
Some babbling about collision detection can be found in Android Breakout (code.google.com/p/android-breakout). Note in particular the comments at the top of findFirstCollision() in GameState.java -- the game steps the ball forward in small increments, checking at each step. You don't need this -- you only have the four walls to worry about, so algebra will provide the answer -- but if you add more objects to collide with you may need something similar. (It also gets more complicated if the collision happens at the edge of the object rather than the center.) - fadden

1 Answers

2
votes

Try to instead cap the value to the border like so

x = Math.max(Math.min(x + mx*speed, GameView.WIDTH), 0.0f));
y = Math.max(Math.min(y + my*speed, GameView.HEIGHT, 0.0f));