How can I make a random CGPointMake, say i created an outlet of a uiimage and called it image, image.center = CGPointMake (//random, //random) everytime second (NSTimer)
Asked
Active
Viewed 1,711 times
3 Answers
2
I'd use arc4random()
in stdlib.h. This utilizes a much more superior algorithm than rand()
. Look up this function in the man pages. You will then want to mod the generated values by the maximum coordinates that you want for both axes.
int x = arc4random() % (int) self.view.frame.size.width;
int y = arc4random() % (int) self.view.frame.size.height;
image.center = CGPointMake(x, y);

csano
- 13,266
- 2
- 28
- 45
-
i am getting an error saying something about not allowing frame in QTWO – user840797 Jul 12 '11 at 15:56
-
Is this code in your controller? If so, put view between self and frame (self.view.frame). – csano Jul 12 '11 at 16:06
-
i have another error saying invalid operands to binary expression (float and CGFloat) – user840797 Jul 12 '11 at 16:13
-
Cast the width/height to an int. – csano Jul 12 '11 at 16:28
-
How can i do that, what does CAST mean? – user840797 Jul 12 '11 at 18:08
1
you can use rand() in stdlib.h
something like:
#include <stdlib.h>
#include <time.h>
srand ( time(NULL) );
int max = 400 // or whatever
int myRandomNumber1 = rand() % max
int myRandomNumber2 = rand() % max
image.center = CGPointMake(myRandomNumber1, myRandomNumber2);

meggar
- 1,219
- 1
- 10
- 18
-
-
if i use this code the image moves far and then SO CLOSE to the place it was before for some reason – user840797 Jul 12 '11 at 16:14
0
Use arc4random()
, you don't even need to seed it.
image.center = CGPointMake(arc4random() % yourView.frame.size.width, arc4random() % yourView.frame.size.height);

Luke
- 7,110
- 6
- 45
- 74
-
if i do the view then it says something about assigning float to CGFloat * i dunno – user840797 Jul 12 '11 at 15:59