CCEaseElasticIn in Cocos2D , iPhone

Yet another animation api from cocos2D, check it out……

 id move = [CCMoveTo actionWithDuration:1 position:ccp(200,250);
 CCEaseElasticIn *elasticIn = [CCEaseElasticIn actionWithAction:move period:2.0];
 [my_sprite runAction:elasticIn ];

Playing sound on the Mac Desktop in Objective C.

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…..

Delete a substring in Objective C, Iphone , Mac………….

This code snippet deletes a substring from a original string..

/** initialize two strings **/
NSString *string = @"This is heaven";
NSString *part = @"heaven";

/** Get the range of the substring in the original string **/
NSRange range = [string rangeOfString:part];

/** Delete the substring from the original string **/
[string deleteCharactersInRange:range];

Please leave your valuable comments………

ToolTip Sound in Adobe AIR/FLEX…

Sometimes we may need to have a sound when we hover over something, i.e when a tooltip appears.
Actually this can be done easily by adding an eventListener to the corresponding control.
Take a look at the example.
This line is the important line.

      myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);

The function myListener gets called when we hover over the label thus producing the sound.
What you have to do is to just copy and paste the following code to your file.

       import mx.events.ToolTipEvent;
     import flash.media.Sound;

     [Embed(source="msgAlert.mp3")]

     private var myToolTipSound:Class;
     private var mySound:Sound;

     private function init():void {
        myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);
        mySound = new myToolTipSound();
     }
      public function playSound():void {
        mySound.play();
     }
     private function myListener(event:ToolTipEvent):void {
        playSound();
     }
  ]]>
   

Encapsulation Using Properties in C#.NET / ASP.NET

Hi,

Let’s see how encapsulation can be implemented using properties in C#.NET/ASP.NET.
Let’s see the code first.

using System;

public class Student
{
    private int stud_id = -1;

    public int ID
    {
        get
        {
            return stud_id;
        }
        set
        {
            stud_id = value;
        }
    }

    private string stud_name = string.Empty;

    public string Name
    {
        get
        {
            return stud_name;
        }
        set
        {
            stud_name = value;
        }
    }
}

public class StudentManagerWithProperties
{
    public static void Main()
    {
        Student studObj = new Student();

        studObj.ID = 7;
        studObj.Name = "Aamir Khan";

	Console.WriteLine(
            "ID: {0}, Name: {1}",
            studObj.ID,
            studObj .Name);

        Console.ReadKey();
    }
}

Ok. Here Student class has two properties ID & NAME. Also two private variables or fields stud_name & stud_id, both are encapsulated by our ID & NAME properties. And also two accessors for setting and getting values from fields. Set accessor set the value to the field. Note that the ‘value’ used here is the keyword! This value is assigned by calling function. StudentManagerWithProperties uses the ID & NAME properties as we can see.

:)

AlertView with textbox in iPhone, Objective C.

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…..

Using GridView in ANDROID….

GridViews are those in which you can arrange elements in a two dimensional grid.
It is what you see in the gallery where images are arranged. Here images are arranged in a two dimensional grid.
Copy the below code and save it as “MyGridView.java”

package com.pack;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MyGridView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(MyGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}

/********************************* End of MyGridView.java ****************************** **/

Now create another file named “Images.java” and copy the below code to it.

package com.pack;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
lass="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">import android.widget.ImageView;
public class Images extends BaseAdapter {
private Context ctxt;
public Images (Context c) {
ctxt = c;
}
public int getCount() {
return Ids.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int pos) {
return 0;
}
public View getView(int pos, View convertView, ViewGroup parent) {
ImageView imgView;
if (convertView == null) {
imgView = new ImageView(mContext);
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
} else {
imgView = (ImageView) convertView;
}
imgView.setImageResource(Ids[pos]);
return imgView;
}
private Integer[] Ids = {
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7
};
}
/*********************************** End of Images.java**************************** **/

Note: Please make sure that you have images named img_0 to img_7 in your res/drawable folder.
Please leave your valuable comments if this post was useful…..

Android TableLayout

In android there are different layouts and we often confuse about which one to use. Even if we select one, it is little complicated.

So this tutorials is to show you about the TableLayout

Here i first created linear Layout in which a Table Layout is added

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TableLayout
		android:layout_width="wrap_content"
		android:id="@+id/table"
		android:layout_height="wrap_content">
	<TableRow>
		<EditText
			 android:text=""
			 android:id="@+id/name"
			 android:layout_column="0"
			 android:hint="name"
			 android:layout_width="wrap_content"
			 android:layout_height="wrap_content"
			 android:fadingEdge="vertical|horizontal"/>
	</TableRow>
	<TableRow>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Save"
			android:layout_column="0"
			android:id="@+id/OkButton"
			android:fadingEdge="horizontal">
		</Button>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Cancel"
			android:layout_column="1"
			android:id="@+id/cancelButton"
			android:fadingEdge="horizontal">
		</Button>
	</TableRow>

	</TableLayout>
</LinearLayout>

Here you can see that the first row ie, the EditText length is limited to 1 column and so it is not looking good. So we can make the EditText span across two column by adding this line to EditText

android:layout_span="2"

Now we can position the TableLayout in the center of the screen by adding this to TableLayout

android:layout_gravity = "center_vertical"

Now we think of aligning this to center horizontal as

android:layout_gravity = "center_horizontal"

But this wont work. This is because of LinearLayout and here the positioning is restricted.
But their is solution “Relative Layout” and positioning is easy by using this layout.

I will cover this in my next Post

Alert Button with Image in Adobe AIR/FLEX…

We usually see only alerts with text only, but in Adobe AIR and FLEX we can have alerts with our images in it. That’s really cool right.
Take a look at this simple example. It places an image in the alert.
Make sure that you have the image named “alert_image.png” in your “src” folder or otherwise give the specific path.



 
        
        


No Image

How to Disable Right Click on HTML page using jQuery ?

Hi,

In some special cases you may need to disable the Right Click option on HTML page you are using.
An easy way to do it using jQuery is follows. Use the following code in the HTML page where you want to disable Right Click.

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

:)

Sorting ArrayList Elements Alphabetically in ASP.NET – Sort()

Hi,
In order to sort elements in ArrayList using ASP.NET we can use the Sort() method.
It will sort ArrayList Elements alphabetically.


This will sort the ArrayList elements alphabetically.

:)

How to play music in cocos2D or Box2D, iPhone?

This simple code plays a music……..


[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@”my_music.mp3″];

For stopping the music use this…….


[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];

To pause the music use this line of code…..


[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];

How to make gear joint in Box2D, iPhone?

Gear joints are one of the real specialities of Box2D.

By creating gear joints between two bodies you can actually simulate a real world gear. For creating a gear joint you need two bodies connected by a revolute or prismatic joint.

The below code creates two bodies in the shape of a circle which is actually attached to the ground. however you can also create joints without joining it with the ground. Here you have to make a ground with possible four fixtures or no fixtures simply creating a body.


        b2Body* body1 = circle1;
        b2Vec2 pos1 = circle1 -> GetPosition();//get position of first body.....
        b2Body* body2 = circle2;
        b2Vec2 pos2 = circle2 -> GetPosition(); // get position of second body....
        revJointDef.Initialize(ground, circle1, pos1);
        b2RevoluteJointDef revJointDef2;
        revJointDef2.Initialize(ground, body2, pos2)//revolute joint is initialized
        joint1 = world->CreateJoint(&revJointDef;); //First joint.....
        revJointDef2.maxMotorTorque = 20000.000000f; //connect a motor to the joint2
        revJointDef2.motorSpeed = 120.000000f / 60; //set the rotation speed.....
        revJointDef2.enableMotor = true;            // enable the motor.....
        joint2 = world->CreateJoint(&revJointDef2;);  //Second joint.....

        gearJointDef.bodyA = body1;
        gearJointDef.bodyA = body2;
        gearJointDef.joint1 = joint1;
        gearJointDef.joint2 = joint2;
        gearJointDef.collideConnected = true;
        gearJointDef.ratio = circleShape2.m_radius/circleShape1.m_radius;
        world->CreateJoint(&gearJointDef;); // this line creates the joint.

Please leave your valuable comments……………………..

Swing JPanel with background image

This code add an image to Jpanel.

JPanel panel1 = new JPanel();
JFrame recursion_frame = new JFrame();

BackgroundPanel stack_image1 = new BackgroundPanel("Recursion.jpg");

panel1.setLayout(null);
panel1.setLayout(new BorderLayout());
panel1.setBackground(Color.lightGray);
panel1.setVisible(true);
recursion_frame.setContentPane(panel1);  ///adding to panel...
recursion_frame.getContentPane().add(stack_image1);  //adding image to panel...

Position swing window in center of the screen

In some case we need to position the window in the center of the screen . The same effect can be achieved by hard coding the center points .But in that case the window position change when the screen resolution changes

This code will position the window in center irrespective of different screen resolutions

public JFrame stack_frame = new JFrame();
stack_frame.setLocationRelativeTo(null);

What is Objective C Keyword id ?

Hi,

Objective C uses a special keyword ‘id’.
Let’s see what it is.
Objective C -id- is actually a ‘pointer to an object’. That is ‘id’ can hold a pointer to any objective c object. It doesn’t matter the object’s class.
eg:

NSString *myString = @"Coderz Heaven!";
id newString;
NSString *tempString;
newString=myString;
tempString=newString;

That’s it! It will work out with using ‘id’ keyword. Compiler simply thinks ‘you know what you are doing!’

A word of caution : Remember not to use * while creating id objects! Because that type already know it’s a pointer!

Read a plist from your resources folder in Iphone Objective C

Plist or property list are usually used for storing data in iPhone.
They are normal XML files, you can open it in a texteditor to view it’s data.
This sample code shows how to read data from the plist.
Reading a plist will return an array.You can print out the array to view the results.


     NSString *path= [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"];
     BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
     if(fileExists){
         NSMutableArray *arr = [[NSArray alloc]  initWithContentsOfFile: path];
         NSLog(@"Data from plist %@",arr);
     }else {
        NSLog(@"File Not Found");
        exit(1);  // if file not found exit the application.
    }

Please leave your valuable comments………

Remove unwanted memory from iPhone….

Hi all ……
You know iPhone doesnot have garbage collection like ANDROID. So it becomes the responsibility of the developer or programmer to release the resources and remove the unwanted textures from your memory.
If you don’t remove the unused textures and other variables from your memory your application will exit after a while.

You often have the problem that your iPhone application exits unexpectedly, Most probably this may be the reason.

One method to check is…….
1. Release variables declared inside a function from there itself.
2. Release other variables inside the dealloc() function.
3. Remove the textures that remain in memory when you use images.
4. If you are using particle effects then don’t use the particle release function.
5. Unload the sounds on dealloc.

For removing the variables you can use..

[my_var release];

For removing the textures from the memory use this code inside the dellaoc function.
Check out the console if it is working. It will show console outputs such as “removing unused texture bla bla bla..”

/** this will remove all the unused frames if you are using sprite sheets **/
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
/** this will remove unused textures of images if you are using only images **/
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
/** this will remove all textures from memory **/
[[CCTextureCache sharedTextureCache] removeAllTextures];

But still your program may exit. This is due to the second line and put only the this line..

[[CCTextureCache sharedTextureCache] removeUnusedTextures];

This may solve your problem…….
This above code will release most of your unused memory.

Please leave your valuable comments if this post was useful…..

Collision Detection In Box2D – Using With Cocos2D

For an interactive game building using Box2D, collision detection of Box2D bodies is necessary. There is an easy way to implement collision detection in Box2D.

For checking whether two bodies have collided with each other in Box2D while using it with cocos2D, then use the following lines of code where ever you want to check collision.

if((contact.fixtureA == sourceFixture && contact.fixtureB == destinationFixture) ||
(contact.fixtureA == destinationFixture && contact.fixtureB == sourceFixture ))
{
//What you want to do after checking the collision?!!!
//That lines of code goes here!
//Simple and Pretty , isn't it?
}

Here you are cheking whether two box2D fixtures are in contact or not! And you can decide which fixtures you need to check for collision.

:)

Removing Forces From Your World in Box2D Cocos2D

Hi,

In certain situations you may need to remove all the forces you have applied on different bodies in your box2D world.
Then what to do?
Removing all the forces from the bodies in the box2D world is simple. Just use the single line of code.

yourWorld->ClearForces();

Here yourWorld is your Box2D world. Simple, isn’t it?

:)

File Operations in Adobe AIR/FLEX

The following example shows how to deal with a simple text file in Adobe AIR/FLEX.
This example illustratesd how to write a string to a text file and save it in the desktop.
However you can use the “application directory” but make sure that you have necessary write permission to access the directory.




	

Please leave your valuable comments…..