Question

I have a ball that bounces around the screen. Based on the level the user has made it to, I make the ball go faster. So, I did the following:

[ball.physicsBody applyImpulse:[self vectorForLevel:self.level]];

The method for building the CGVector.

- (CGVector)vectorForLevel:(int)level {
    CGFloat thrust = level+3;
    return CGVectorMake(thrust*cosf(4), thrust*sinf(-4));
}

While this works really well and speeds up for each level like I want to, I would also like to randomize the angle that the balls starts at, but I am not sure how to do that.

I don't understand enough about CGVector to really know how to change the angle. Are the 4 and -4 that I threw in there the angle?

Does anyone know how to randomize the direction?

Was it helpful?

Solution

The expressions you're using inside CGVectorMake() are essentially a conversion from polar coordinates to cartesian.

The x component is given by radius * cos(theta), where theta is the angle in radians. y is radius * sin(theta). Zero angle generally points to the right ("due east").

Thus, just change theta to change the direction of your vector. (It's most sensible to pass the same number to both cosf() and sinf(), but of course you'll get some result no matter what you use.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top