Moving a ball randomly

I am trying to move a ball across the screen with random coordinates . but my object moves just around x axis ! here is my code :

 [UIView beginAnimations:nil context:nil];
 [UIView setAnimationDuration:0.70];
 [UIView setAnimationRepeatCount:1000];
 [UIView setAnimationRepeatAutoreverses:YES];

 CGFloat x = (CGFloat) random()/(CGFloat) RAND_MAX;
 CGFloat y = (CGFloat) random()/(CGFloat) RAND_MAX;

 CGPoint squarePostion = CGPointMake(y, x);
 blue3.center = squarePostion;

 [UIView commitAnimations];

EDITED :

I change my code to this but doesn't work ~:

CGFloat x = (CGFloat) random()/(CGFloat) RAND_MAX * self.view.bounds.size.width;
CGFloat y = (CGFloat) random()/(CGFloat) RAND_MAX * self.view.bounds.size.height;

CGPoint squarePostion = CGPointMake(y, x);

same happens !

Answers


You scale all your values to 0...1, so I'd expect your ball to actually move to (0,0) and stay there. Also, you might have your x any y coordinates swapped in CGPointMake. You need to scale your value to the region you want it to be in. For a random position all over your view (if blue3 is a subview of containerView - which might be self here):

 CGFloat x = (CGFloat) random()/(CGFloat) RAND_MAX * containerView.bounds.size.width;
 CGFloat y = (CGFloat) random()/(CGFloat) RAND_MAX * containerView.bounds.size.height;

 CGPoint squarePostion = CGPointMake(x, y);

Need Your Help

How to make Datebox Jquery Mobile Input field clickable?

javascript jquery css jquery-mobile datebox

I have two date fields. Field 2 works fine. Clicking anywhere on the input type date for second fields opens the calendar. But the same is not working for first date field. When I click on the cale...

iPhone6 view size is samller with autolayout

ios iphone autolayout iphone-6

I have added autolayout but no size class.. I get this in iPhone 6 simulator..