I've started trying a few things with Sprite Kit for Game Development. I was creating a brick breaking game. So I've run into a issue on how to randomize the initial starting direction of the ball.

I set the following properties for my ball which launches from the paddle.

ball.physicsBody.friction = 0;
ball.physicsBody.linearDamping = 0;
ball.physicsBody.restitution = 1 ; //energy lost on impact or bounciness

To start at different direction during the gameplay, I've randomized the selection of the 4 vectors because I'm using the applyImpulse method to direct the ball in a particular direction and I need to make sure the ball does not go slow if the vector values are low.

int initialDirection = arc4random()%10;
CGVector myVector;

if(initialDirection < 2)
    myVector = CGVectorMake(4, 7);
else if(initialDirection >3 && initialDirection <= 6)
    myVector = CGVectorMake(-7, -5);
else if(initialDirection >6 && initialDirection <= 8)
     myVector = CGVectorMake(-5, -8);
     myVector = CGVectorMake(8, 5);
//apply the vector
[ball.physicsBody applyImpulse:myVector];

Is there any way I can randomize the direction and still maintain a speed for my ball ?


You could instead get a random angle (within some range) and then use that for the initial direction of the ball. Something like:

// min angle: 10, max angle: 170
int min_angle = 10;
int max_angle = 170;
int degrees = arc4random_uniform(max_angle - min_angle) + min_angle;
float radians = degrees * M_PI/180.0f;
myVector = CGVectorMake(cos(radians), sin(radians));

This will be a unit direction vector though, so, you would want to multiply this by whatever amount of force you want in this direction.

| improve this answer | |
  • 2
    \$\begingroup\$ Shouldn't that be arc4random_uniform(max_angle -min_angle) +min_angle? This way if arc4random gives 170 (the maximum), you'd add 10 to it and get 180, which is > max_angle. \$\endgroup\$ – uliwitness Nov 14 '14 at 1:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.