views:

137

answers:

1

I am creating a bouncing object that can bounce around a 2D rectangular room. I have read through the answer of the other question about using velocityX and velocityY instead of normal direction angle. OK, it sounds easier so I implement the following mathematical methods below. However, there is one difference. I required that I input an angle and which (horizontal/vertical) wall the object is hit.

+(double) getDirection:(double) x1:(double) y1: (double) x2: (double) y2{
    return (atan2(y2-y1,x2-x1) * 180) / 3.14;
}
+(double) getLengthDir_X:(double) dis: (double) dir{
    return (dis*cos(dir));
}
+(double) getLengthDir_Y:(double) dis: (double) dir{
    return (dis*sin(dir));
}

+ (float) getBouncedAngle: (float) dir: (int) HVVar{

    if (dir < 0)dir+=360;
    else if (dir >= 360)dir-=360;

    NSLog(@"in dir %f", dir);

    float initialVX = [self getLengthDir_X:100 :dir],
    initialVY = [self getLengthDir_Y:100 :dir];

    NSLog(@"x,y %f %f", initialVX, initialVY);

    if (HVVar == 0){//horizontal wall
     initialVX = -initialVX;
    }else if (HVVar == 1){//vertical wall
     initialVY = -initialVY;
    }

    NSLog(@"x,y %f %f", initialVX, initialVY);

    float newDir = [self getDirection:0 :0 :initialVX :initialVY];

    NSLog(@"dir : %f ---> dir : %f", dir, newDir);

    return newDir;
}

But I get very strange results. I get wrong angles sometimes. Am I missing something?

2009-08-13 23:31:19.854 X[2936:20b] in dir -0.049634
2009-08-13 23:31:19.854 X[2936:20b] x,y 99.876846 -4.961388
2009-08-13 23:31:19.855 X[2936:20b] x,y -99.876846 -4.961388
2009-08-13 23:31:19.857 X[2936:20b] dir : -0.049634 ---> dir : -177.246017
2009-08-13 23:31:21.220 X[2936:20b] in dir -177.246017
2009-08-13 23:31:21.220 X[2936:20b] x,y 25.124613 -96.792320
2009-08-13 23:31:21.221 X[2936:20b] x,y -25.124613 -96.792320
2009-08-13 23:31:21.222 X[2936:20b] dir : -177.246017 ---> dir : -104.604294
2009-08-13 23:31:21.253 X[2936:20b] in dir -104.604294
2009-08-13 23:31:21.253 X[2936:20b] x,y -59.644127 80.265671
2009-08-13 23:31:21.255 X[2936:20b] x,y 59.644127 80.265671
2009-08-13 23:31:21.256 X[2936:20b] dir : -104.604294 ---> dir : 53.411633
+2  A: 

Your sin and cos functions expect arguments in radians. You're giving them arguments in degrees.

Beta
I see. Carelessness. Thank you.
unknownthreat