Question

So this is my first practice game I'm developing and first time using accelerometer so apologizes in advance if the answer is obvious. Would also like answered with code and explanation.

So part of game I have a ball being rolled around no the screen. The ball moves according to the tilt. The device orientation for this app is only landscape right. When I tilt the phone up and down while holding the phone landscape right the ball moves accordingly. (tilt the top end down the ball rolls up, tilt the bottom end down the ball rolls down). So those 2 tilts are fine. Now when I tilt the screen left side down the ball rolls right and vice versa. What I want is the screen to tilt left and the ball to go left and tilt the screen right and the ball goes right. How is this fixed with my code below. I know its as simple as changing two lines probably.

//delegate method
-(void)outputAccelertionData:(CMAcceleration)acceleration
{
    currentMaxAccelX = 0;
    currentMaxAccelY = 0;


    if(fabs(acceleration.x) > fabs(currentMaxAccelX))
    {
        // this needs to be currentMaxAccelY not currentMaxAccelX for those of you thinking this is the solution
        currentMaxAccelY = acceleration.x; 
    }
    if(fabs(acceleration.y) > fabs(currentMaxAccelY))
    {
        // this needs to be currentMaxAccelX not currentMaxAccelY for those of you thinking this is the solution
        currentMaxAccelX = acceleration.y;
    }
}

-(void)update:(CFTimeInterval)currentTime {

    /* Called before each frame is rendered */


    float maxY = 480;
    float minY = 0;


    float maxX = 320;
    float minX = 0;

    float newY = 0;
    float newX = 0;

    //Im pretty sure the problem is in this if statement as this is what deals with the left and right tilt
    if(currentMaxAccelX > 0.05){
        newX = currentMaxAccelX * 10;
    }
    else if(currentMaxAccelX < -0.05){
        newX = currentMaxAccelX*10;
    }
    else{
        newX = currentMaxAccelX*10;
    }

    newY = currentMaxAccelY *10;

    newX = MIN(MAX(newX+self.ball.position.x,minY),maxY);
    newY = MIN(MAX(newY+self.ball.position.y,minX),maxX);


    self.ball.position = CGPointMake(newX, newY);

}
Was it helpful?

Solution

So I solved the problem. The issue was with my math. Instead of multiplying by 10 I should have been multiplying by negative 10 to get in the inverse effect.

if(currentMaxAccelX > 0.05){
        newX = currentMaxAccelX * -10;
    }
    else if(currentMaxAccelX < -0.05){
        newX = currentMaxAccelX*-10;
    }
    else{
        newX = currentMaxAccelX*-10;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top