Hi everybody I making an Xcode App but have now been stuck for 2 days
in my app I have to create some images (which balls) in the amount stated by the user .
e,g if the user says make 10 10 balls should appear on the same screen at random locations I know to make location random but can't figure how to do it ... how do i connect to the interface builder ???
tried this
1.h
UIImageView *c[100];
1.m
for (int i = 0; i < "users value" ; i++) {
float x = (float)(67 + ((95 + 22) * i));
UIImageView *c[i] = [[UIImageView alloc]
initWithFrame:CGRectMake(x, 20.0f, 95.0f, 149.0f)];
[ballsView[i]setImage:[UIImage imageNamed:#"1.png"]];
ballsView[i].opaque = YES;
ballsView[i].hidden = NO; /* change to YES for distribution */
}
use this. hope helps
for (int i = 0; i < "users value" ; i++)
{
float x = (float)(67 + ((95 + 22) * i));
UIImageView *c[i] = [[UIImageView alloc]
initWithFrame:CGRectMake(x, 20.0f, 95.0f, 149.0f)];
c[i].image=[UIImage imageNamed:#"1.png"]];
[ballsView[i] addSubView:c[i]];
ballsView[i].opaque = YES;
ballsView[i].hidden = NO; /* change to YES for distribution */
}
Related
I want to set 5 buttons on uiview at random position. Buttons need maintain some spacing to each other. I mean buttons should not overlap to each other.
All buttons set on UIView come from corners with rotation animation.
btn1.transform = CGAffineTransformMakeRotation(40);
btn2.transform = CGAffineTransformMakeRotation(60);
btn3.transform = CGAffineTransformMakeRotation(90);
btn4.transform = CGAffineTransformMakeRotation(30);
btn5.transform = CGAffineTransformMakeRotation(20);
I Can rotate buttons using above code but can you pls. help me for set buttons on random position with out overlapping by each other.
If points are fix than I can set buttons with animation by this code but I want random position of buttons.
[AnimationView moveBubble:CGPointMake(18, 142) duration:1 : btn1];
[AnimationView moveBubble:CGPointMake(118, 142) duration:1 : btn2];
[AnimationView moveBubble:CGPointMake(193, 142) duration:1 : btn3];
[AnimationView moveBubble:CGPointMake(18, 216) duration:1 : btn4];
Thanks in advance.
1st, add buttons to an NSArray, only to make things easier:
NSArray *buttonArray = #[btn1,btn2,btn3,btn4,btn5];
Now, this code tries to Arrange them at random positions.
int xTemp, yTemp;
for (int i = 0; i < 5; i++) {
while (YES) {
xTemp = arc4random_uniform(view.frame.size.width - [buttonArray[i] frame].size.width);
yTemp = arc4random_uniform(view.frame.size.height - [buttonArray[i] frame].size.height);
if (![self positionx:xTemp y:yTemp intersectsAnyButtonTillIndex:i inButtonArray:buttonArray]) {
[AnimationView moveBubble:CGPointMake(xTemp, yTemp) duration:1 : buttonArray[i]];
break;
}
}
}
Implement this function somewhere too:
- (BOOL) positionx:(int)xTemp y:(int)yTemp intersectsAnyButtonTillIndex:(int)index inButtonArray:(NSArray *)buttonArray {
//Again please change the < to <= , I'm sorry, doing too many things at once.
for (int i = 0; i <= index; i++) {
CGRect frame = [buttonArray[i] frame];
//EDIT : In the logic earlier, I had wrongly done a minus where I should have done a plus.
if ((xTemp > frame.origin.x && xTemp < (frame.size.width + frame.origin.x)) && (yTemp > frame.origin.y && yTemp < (frame.size.height + frame.origin.y))) return YES;
}
return NO;
OK this is a workign soln., I hope, just added something to WolfLink's answer. Check This.
for (UIButton *button in buttonArray) {
button.frame = CGRectMake(arc4random_uniform(view.frame.size.width - button.frame.size.width), arc4random_uniform(view.frame.size.height - button.frame.size.height), button.frame.size.width, button.frame.size.height);
while ([self button:button intersectsButtonInArray:buttonArray]) {
button.frame = CGRectMake(arc4random_uniform(view.frame.size.width - button.frame.size.width), arc4random_uniform(view.frame.size.height - button.frame.size.height), button.frame.size.width, button.frame.size.height);
}
//another function
-(BOOL)button:(UIButton *)button intersectsButtonInArray:(NSArray *)array {
for (UIButton *testButton in array) {
if (CGRectIntersectsRect(button.frame, testButton.frame) && ![button isEqual:testButton]) {
return YES;
}
}
return NO;
}
Based on spiritofmysoul.wordpress's code:
//in the function where you randomize the buttons
NSArray *buttonArray = #[btn1,btn2,btn3,btn4,btn5];
for (UIButton *button in buttonArray) {
float widthOffset = self.frame.size.width-button.frame.size.width;
float heightOffset = self.frame.size.height-button.frame.size.height;
button.frame = CGRectMake(arc4random()%widthOffset, arc4random()%heightOffset, button.frame.size.width, button.frame.size.height);
while ([self button:button intersectsButtonInArray:buttonArray]) {
button.frame = CGRectMake(arc4random(), arc4random(), button.frame.size.width, button.frame.size.height);
}
//another function
-(BOOL)button:(UIButton *)button intersectsButtonInArray:(NSArray *)array {
for (UIButton *testButton in array) {
if (CGRectIntersectsRect(button.frame, testButton.frame) && ![button isEqual:testButton]) {
return YES;
}
}
return NO;
}
Beware: This will work well for small amounts of buttons on a large space but as you add buttons and you run out of space, this method will take much longer to run. If there is not enough space for all the buttons, it will become an infinite loop.
Here some code for Add sprite for Enemies.....
_robbers = [[CCArray alloc] initWithCapacity:kNumAstroids];
for (int i = 0; i < kNumAstroids; ++i) {
CCSprite *asteroid = [CCSprite spriteWithSpriteFrameName:#"robber.png"];
asteroid.visible = NO;
[_batchNode addChild:asteroid];
[_robbers addObject:asteroid];
}
And in Update method ........
double curTime = CACurrentMediaTime();
if (curTime > _nextRunemanSpawn) {
float randSecs = [self randomValueBetween:0.20 andValue:1.0];
_nextRunemanSpawn = randSecs + curTime;
float randY = [self randomValueBetween:80 andValue:80];
float randDuration = [self randomValueBetween:4.5 andValue:4.5];
float randDuration1 = [self randomValueBetween:1.0 andValue:1.0];
CCSprite *asteroid = [_robbers objectAtIndex:_nextRobber];
_nextRobber++;
if (_nextRobber >= _robbers.count) {
_nextRobber = 1;
}
[asteroid stopAllActions];
asteroid.position = ccp(winSize.width +asteroid.contentSize.width / 2 , randY);
asteroid.visible = YES;
[asteroid runAction:[CCSequence actions:[CCMoveBy actionWithDuration:randDuration position:ccp(-winSize.width-asteroid.contentSize.width, 0)],
[CCCallFuncN actionWithTarget:self selector:#selector(setInvisible:)],nil]];
All Sprites are Move from right to left in screen
when Sprite crosses the middle of the screen it automatically disappear
what is the reason for this problem ??
I agree with the previously mentioned statement from LearnCocos2D. It is also possible that you are adding multiple objects and reaching the end of the capacity in the line
_robbers = [[CCArray alloc] initWithCapacity:kNumAstroids];
If you try to spawn more objects than whatever number you have specified for kNumAsteroids it will remove the oldest object and use the new one in its place. I.e. if kNumAsteroids is 5, you have 5 on the screen and then add a sixth, 1 will become 6 and its position will be whatever you set it to.
else if (setIndexPath == 4)
{
viewWithButtons.frame = CGRectMake(5, 40, 310, 390);
int ch = 6;
int cv = 6;
for ( int i = 0 ; i < cv ; ++i )
{
for ( j = 0 ; j < ch ; ++j )
{
btnMatrix = [[[UIButton alloc] initWithFrame:CGRectMake(10+pw*j, 51+ph*i, width, height)] autorelease];
btnMatrix.tag = i*ch+j;
btnMatrix.userInteractionEnabled = TRUE;
[btnMatrix addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchDown];
[btnMatrix setBackgroundImage:imgDefaultBG forState:UIControlStateNormal];
[viewWithButtons addSubview:btnMatrix];
[arrButton addObject:btnMatrix];
}
}
}
[self.view addSubview:viewWithButtons];
I am generating buttons dynamically according to the selected matrix, like 4 * 4, 4 * 5, 4 * 6, 5 * 6, 6 * 6 etc....
Buttons are completely set as per the selected matrix from above (the code is for 6 * 6 matrix).
Now i have to set random background images of these buttons.
I am not able to set this kind of dynamic buttons' background.
is there any effective way to set backgrounds dynamically in random order for each separate buttons?
for (intimg = 1; intimg <= 15; intimg++)
{
arr_FirstSet = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"%d_f_2.png",intimg], nil];
}
for (intimgSET2 = 1; intimgSET2 <= 15; intimgSET2++) {
arr_SecondSet = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"%d_s_2.png",intimgSET2], nil];
}
I am adding images in this format to the NSMutableArray.
How to pick random image from the above used arrays. I have to match both arrays images & give the result on buttons. If both matches, suppose i press on one button it will display 1_f_2.png & on another button press it will display 1_s_2.png (as background)then both of these buttons will be removed from the view.
I had tried many logics to get this.
I am not getting exactly what i am interested to do on touchdown of button.
Please suggest any code snippet or link or code also.
Thanks in advance.
- (UIImage*)randomImage {
NSInteger imageCount = [[self imageArray] count]
return [[self imageArray] objectAtIndex:arc4random() % imageCount];
}
If you want matching pairs. Use dictionary with two images, or simple class holding two images.
I have many no. of buttons on my view and I want to shuffle the buttons(change in position) then how can I shuffle the button in my view.
use arc4random()
and change position of your buttons
In your .h file : UIButton *buttonsarray[10];
In your .m file :
// Make array of button using following way.I used this method to creates button and you can use yours.
- (void)viewDidLoad {
[super viewDidLoad];
float y = 5;
int x = 0;
int count = 0;
for (int i = 0 ; i < 10; i++)
{
count ++;
buttonsarray[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonsarray[i].frame = CGRectMake(x, y, 100, 100);
[buttonsarray[i] setTitle:[NSString stringWithFormat:#"%d",i+1] forState:UIControlStateNormal];
x = x + 105;
[self.view addSubview:b[i]];
if(count == 3)
{
count = 0;
x = 0;
y = y+ 105;
}
}
}
// This function will soufflé your buttons
- (IBAction)btnClicked:(id)sender
{
int n = 10;
int swaper;
for (int i = 0 ; i < 10 ; i++)
{
int r = arc4random()%n;
if(r != swaper){
swaper = r;
CGRect r1 = buttonsarray[i].frame;
buttonsarray[i].frame = buttonsarray[swaper].frame;
buttonsarray[swaper].frame = r1;
n--;
}
}
}
Hope,this will help you..
You can do this
Make an Array with a group of CGPoints you will need to store the points as strings.
In the layoutSubViews method set something like this:
-(void)layoutSubViews{
[self.subviews enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
CGPoint newPoint = CGPointFromString([positionsArray objectAtIndex:idx]);
object.frame = CGRectMake(newPoint.x,newPoint.y,object.frame.size.width,object.frame.size.height);
}];
}
Then you will need to shuffle the positions in the positions array, you can see an example method here :How to Shuffle an Array
Now every time you need to Shuffle the positions you can call -(void)setNeedsLayout on your view.
There are more options but that was the first I thought of.
Good Luck
I have added some sprite by using the following code and then by checking the rect
intersection I want to replace these sprites with another one.Can you help me out by providing code
to replace these random images.Problem is that the image to be replaced is also taken
randomly.........
yp = 40;
//CCSprite *spr;
movableSprites = [[NSMutableArray alloc] init];
for(int m=0; m<4; m++)
{
do
{
i = 'a';
//NSLog(#"valueeeeeeeee %d",i);
next = arc4random()%maxalphabets;
//NSLog(#"valueeeeeeeeenexttttt %d",next);
i+=next;
//NSLog(#"valueeeeeeeee %d",i);
spr = (CCSprite*)[self getChildByTag:i];//checks if found alreadyyyyyy
NSLog(#"Strrrrrrrr is:%#",spr);
}while(spr);
spNameStr = [NSString stringWithFormat:#"%c3.png",i];
NSLog(#"tagggg %d",i);
NSLog(#"spNameStr is:%#",spNameStr);
spr = [CCSprite spriteWithFile:spNameStr ];
spr.tag = i;
//NSLog(#"tagiiiiii %d",i);
spr.position = ccp(60,yp);
[self addChild:spr z:2];
[movableSprites addObject:spr];
yp+=spr.contentSize.height+35;
}
yp = 40;
NSMutableArray *answerimagesCopy = [NSMutableArray arrayWithArray:movableSprites];
NSLog(#"answer image copy elements areeeee %#",answerimagesCopy);
for(k = 0; k < movableSprites.count; ++k)
{
NSLog(#"inside forrrr");
int j=arc4random()%([answerimagesCopy count]);
NSLog(#"valueee of jjjjjjjj %d",j);
CCSprite *ansimage = [answerimagesCopy objectAtIndex:j];
//NSLog(#"................ %#",ansimage);
p=ansimage.tag;
NSLog(#"tagg..... %d",p);
[answerimagesCopy removeObjectAtIndex:j];
//NSLog(#"tagg..... %d",j);
spNameStr = [NSString stringWithFormat:#"%c4.png",p];
NSLog(#"spNameStr is:%#",spNameStr);
//NSLog(#"tagggg %d",j);
spr = [CCSprite spriteWithFile:spNameStr ];
spr.tag = p+100;
spr.position = ccp(260,yp);
[self addChild:spr z:1];
yp+=spr.contentSize.height+35;
}
I have did this using sprite sheet. if you can create a sprite sheet and then assign that sprite sheet to CCSpriteBatchNode's object like
$ CCSpriteBatchNod * m_meteoritesSprites =[CCSpriteBatchNode batchNodeWithFile:#"Meteo.pvr.ccz"];
and then load plist
$[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"Meteo.plist"];
and then use sprite frames to assign images to your sprite like
$ m_meteoritesSprites =[CCSpriteBatchNode batchNodeWithFile:#"Meteo.pvr.ccz"];
i used TexrturePacker to make sprite sheets
hope this helps you.