Hi,
If you want to scroll a UIScrollView programatically as the result of any IBOutlet actions, use the following code in that particular action.
[yourScroller setContentOffset:CGPointMake(0,250) animated:YES];
This will scroll your scroller named ‘yourScroller’ automatically to the point specified!
Hello all……
We may need to know that what is your current device orientation.
Using the below code you can do this.
if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
NSLog(@"Device is now in Portrait Mode");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
NSLog(@"Device is now in LandscapeLeft Mode ");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
NSLog(@"Device is now in LandscapeRight Mode");
}
else if([[UIDevice currentDevice]orientation] ==
kCCDeviceOrientationPortraitUpsideDown) {
NSLog(@"Device is now in PortraitUpsideDown Mode");
ss="Apple-style-span" style="font-weight: normal;">
}
Note: If you have to explicitly set the orientation of your phone to any of the above you can set this in the appDelegate.m file. You can put an “||” (OR) symbol in between to set more than one.
Please leave your valuable comments if this post was useful…..
Hi,
Setting a background image to the UITableView will make it looks great! Use the following code to set a background image to a UITableView.
UIImage *bgImage= [UIImage imageNamed:@"sampleImage.png"];
UIImageView *bgView= [[UIImageView alloc] initWithImage:bgImage];
urTblView.backgroundView = bgView;
Here ‘urTblView’ is your UITableView.
You can simulate any animations if you have a sequence of images which makes the illusion of that
animations and rendering those images to the screen. In cocos2D it can be done in two ways, with sprite sheet
animation and without sprite sheets. Here we are going to see how it can be done with out sprite sheet.
CCAnimation *sitDown = [CCAnimation animationWithName:@"sitDown" delay:0.1f];
[sitDown addFrameWithFilename:@"sit1.png"];
[sitDown addFrameWithFilename:@"sit2.png"];
[mySprite addAnimation:sitDown];
id sitAction = [CCAnimate actionWithAnimation:sitDown restoreOriginalFrame:YES];
[yourSprite runAction:sitAction];
Here CCAnimation holds a series of images known as Frames and CCAnimate is simply the action which will run the
CCAnimation. Simple.
Suppose that we have two images named, sit1.png and sit2.png which simulates a sitting animation of our sprite. First
we have added that images/frames to our CCAnimation object sitDown. Then we CCAnimate our CCAnimation frames and
deploy those actions to our sprite. We can set the delay time between the individual frames in CCAnimation. Also we can restore the original image before sprite animation after animatin completes or not!That’s it.
We will later see in here how Sprite Animations can be done by using Sprite Sheets. Keep in touch.
Today I will talk about building games for android and iPhone.
There are a lot of SDK’s available for building games over the internet and I am here to talk about the CORONA SDK.
Corona SDK is a software development kit created by Walter Luh, co-founder of Ansca Mobile. It allows software programmers to build mobile applications for the iPhone, iPad, and Android devices.
Corona lets developers use integrated Lua, layered on top of Objective-C, to build graphically rich applications that are also lightweight in size and quick in development time. The SDK does not charge per-app royalty or impose any branding requirement, and has a subscription-based purchase model that allows new features to be rolled out immediately to user
Check out this site for more information about corona
http://www.anscamobile.com/corona/
You can also some of our tutorials also here.
In the coming posts we will be adding more about coding in Corona.
Check out this link to get access to the corona documentation.
Hi,
For calling a function after a definite time interval in Cocos2D, use the following code.
[self performSelector:@selector(yourFunction) withObject:nil afterDelay:7.0];
this will call the function ‘yourFunction’ after 7 seconds.
Hi,
For adding a custom font in a UITextView, use the following code.
IBOutlet UITextView *myTextField;
[myTextField setFont:[UIFont fontWithName:@"Helvetica" size:20]];
Hi,
For showing particle effects repeatedly in Cocos2D, use the sample code.
CCParticleSystemQuad *yourParticleEffect = [CCParticleSystemQuad particleWithFile:@"yourEffect.plist"];
[self addChild:yourParticleEffect z:5];
This will show the effect ‘yourEffect’ repeatedly in your game.
Hi,
In order to make a UITextField with out or no border, do like this.
In your .h class file,
IBOutlet UITextField *urTextField;
In your .m class file,
urTextField.borderStyle = UITextBorderStyleNone;
Thus you will get a UITextField named urTextField without border.
Hi,
Use the following line of code to convert NSData to NSString in iPhone/iPad using Objective C.
NSString *convertedString =[ [NSString alloc]initWithData:yourData];
Here ‘yourData’ is your NSData which you want to convert to NSString.
Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *urtouch = [touches anyObject];
NSUInteger urtapCount = [urtouch tapCount];
switch (urtapCount) {
case 1:
NSLog(@"Single Tap Detected!");
break;
case 2:
NSLog(@"Double Tap Detected!");
break;
case 3:
NSLog(@"Triple Tap Detected!");
break;
default :
break;
}
}
Try it out! You can even detect Quadrup!
Hi,
Sometimes you may need to find the distance between two CGPoint in cocos2D or box2D using Objective C. See the following code to see how you could do that.
CGPoint first= CGPointMake(50,50);
CGPoint second= CGPointMake(200,200);
float maxDistance= ccpDistance(first, second);
Hi,
Sometimes you may want to detect shake gesture in iPhone using your programs. But how can you detect shake gesture in iPhone? Shake gesture in iPhone can be detected by using the accelerometer. The following lines of code can be used for detecting the shake gesture in iPhone. You can use these lines of code in your cocos2D applications/games.
First of all you MUST enable accelerometer in the init function
isAccelerometerEnabled = YES;
Then use the following function to detect the shake gesture.
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
if(abs(acceleration.x-oldX )>0.7 || abs(acceleration.y-oldY)>0.7)
{
NSLog(@”Yupie! Shake detected!”);
}
oldX = acceleration.x;
oldY = acceleration.y;
}
Here oldX & oldY are variables that store accelerometer values and 0.7 is the value you are giving to check for shake gesture. That’s it.
Hi,
If you are a game developer and you are using box2D for real world simulations, you would probably need a particular body to be removed from the box2D world! But how can you remove box2D body from world ? See the following sample code which does the same.
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//Getting Touch Locations
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
//Converting to cocos2D positioning
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
//Getting body list from world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
//Getting Fixture from the bodies
b2Fixture *bf1 = b->GetFixtureList();
//Checking whether the fixture contains touch location!
if (bf1->TestPoint(locationWorld)) {
//If YES assigning user data to a sprite tempSprite
CCSprite *tempSprite = (CCSprite *) b->GetUserData();
//Checking whether the user data sprite tag is 7
if (tempSprite .tag==7) {
//If YES then remove the sprite & the body!
[self removeChild:tempSprite cleanup:YES];
world->DestroyBody(b);
}
}
}
}
Here tag 7 is what we previously assigned for the sprite corresponding to the body’s user data!
Hi,
In order to verify an email address you have entered is valid or not using Objective C, use the following code.
- (BOOL) checkYourMail: (NSString *) myEmail{
NSString *checkMail= @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}";
NSPredicate *matchMail = [NSPredicate predicateWithFormat:@"Matching %@", checkMail];
return [matchMail evaluateWithObject:myEmail];
}
Hi,
In certain situations you may need to make visible or invisible certain sprites. But how to set a sprite visible and invisible in Cocos2D? See the following Cocos2D code.
//Set the sprite's visible value to 1 to make it visible
yourSprite.visible = 1;
//Set the sprite's visible value to 0 to make it invisible
yourSprite.visible = 0;
Hi,
There may arise some situations where you need to change the z value of a particular sprite during an action in Cocos2D. So how can you do that? See the following lines of code.
CCSprite *sample= [CCSprite spriteWithFile:@"trialImage.png"];
sample.position = ccp(160,240);
[self addChild:sample z:1];
/* Some of your actions goes here! */
[self reorderChild:sample z:9];
This will re order the sprite’s tag to 9 from 1 after ‘your actions’.
Hi,
Want to invoke an action when a text field (UITextField) is clicked using Objective C? Use the following.
[myTextField addTarget:self action:@selector(textFieldTouched:) forControlEvents:UIControlEventTouchDown];
- (void) textFieldTouched:(id)sender {
//Here goes your actions on TextField Clicked
}
Hi,
Sometimes you may need to create some buttons to the View using Objective C code rather than using Interface Builder. Here is how you can do that easily and efficiently.
//You can create button with type. Here I am creating a Custom Button
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
//Then what? Give action to be performed on it!
[myButton addTarget:self action:@selector(newAction:)
forControlEvents:UIControlEventTouchUpInside];
//Giving Background, Frame & Title to the button
myButton.frame = CGRectMake(0, 0, 80, 40);
[myButton setBackgroundImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal];
[myButton setTitle:@"Go Next!" forState:UIControlStateNormal];
//Finally what?? Add it to the View
[self.view addSubview:myButton];
You can create any number of UIButtons like this!
Hi,
If you want to split a string between a symbol like, ‘.’ or ‘-’ or ‘,’ in Objective C, what to do?
See the code for how to split string in Objective C.
NSString *myString = @”song.mp3”;
NSArray *splitArray = [myString componentsSeparatedByString:@”.”];
This code will split the string ‘myString’ into ‘song’ & ‘mp3′ (separated by ‘.’) and stores in the splitArray indices 0 & 1 respectively.
Hi,
In one of our previous post we have discussed how to animate sprite sheet in cocos2D.
In some cases you may need to stop the sprite sheet animation abruptly. How to do that?
Here the way to do that. Use the following.
[spriteName stopAction:spriteNameAction];
where spriteName is the name of your sprite & spriteNameAction is the name of your sprite sheet animation action.
Hi,
While using Box2D , in many cases you may need to connect two bodies together. But the collision between them during motion is not what you preferred! So how can you prevent those bodies being connected in Box2D from collision?
Use the line of code to prevent the collision.
jointDef.collideConnected = false;
Hi,
Suppose you want to copy a sprite image to another new sprite while using cocos2D. What you do?
See the following code…
Let oldSprite be your first sprite
CCSprite *oldSprite = [CCSprite spriteWithFile:@"ImgOne.png"];
And newSprite be your second sprite
CCSprite *newSprite = [CCSprite spriteWithTexture:[oldSprite texture]];
That’s it! Done! Now newSprite too contain ImgOne as Sprite.
There are different ways for playing sound on the Mac in Objective C.
Let’s look at some of the methods..
1. Play by filename.
NSSound *mySound = [NSSound soundNamed:@"sound"];
if you have no file named “sound” in your application’s main bundle, then it will return nil.
2. Play by pathName
sound = [[NSSound alloc] initWithContentsOfFile:@"/Volumes/Audio/sound.aiff"
byReference:YES];
3. Play by URL
NSURL *soundURL = [NSURL
fileURLWithString:@"file://~/soundfiles/sound.aiff"];
NSSound *sound = [[NSSound alloc] initWithContentsOfURL:soundURL
byReference:NO];
Then to play the sound add
if (![sound isPlaying])
[sound play];
To pause the sound
[sound pause];
To stop the sound.
[sound stop];
To resume the sound
[sound resume];
Please leave your valuable comments if this post was useful…..
Often we see alerts with text message or title in it.
But actually we can customize alerts. We can place any views inside it.
We can place a textView(TextField) , imageView etc in it.
Take a look at this simple example that places a textbox inside an alertView.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title goes here!!"
message:@"My Message"
delegate:self cancelButtonTitle:
@"Cancel" otherButtonTitles:@"OK", nil];
UITextField *TF = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[TF setBackgroundColor:[UIColor ClearColor]];
[alert addSubview:TF]; /** adding the textfield to the alertView **/
[alert show];
[alert release];
Please leave your valuable comments…..