Sunday, June 7, 2015

Performing Segue and Passing data in iOS

I was trying to learn how to perform view switching using Segue for UI created by StoryBoard. Using Segue is quite easy and convenient. You can create Segue from Interface Builder, which associate action to view. Like if you click some button then you can associate this click action with view switch and you can select which view to switch to. This all is quite simple and can be done using simple drag and drop.

In case you want to perform view switch manually without any user interaction, you can call "performSegueWithIdentifier", like below. Here once my game is finished, I am calling "GameOverSegue", which will switch view to GameOver view.
self.performSegueWithIdentifier("GameOverSegue", sender: self)
If you want to pass some data while performing Segue, your calling ViewController needs to override "prepareForSegue" function. In this function you can set data to called view. Like below, I want to pass score to my GameOver view.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if( segue.identifier == "GameOverSegue") {
        let gameOverVC: GameOverViewController = 
            segue.destinationViewController as! GameOverViewController;
        gameOverVC.setScore(self.score)
    }
}
Thanks, hope this will be helpful.

Saturday, June 6, 2015

Drawing round border around UIView in iOS

I wanted to create a subview UIView with round border in iOS. I found following code works very well to draw round border around UIView. While this code is written swift you can easily write similar code in Objective C as well.

Following is the code. As you can see, I selected subview UIView and made is IBOutlet using Interface Builder. Once that is done you can see round border around view.

@IBOutlet weak var contentView: UIView?
    
override func viewDidLoad() {
    super.viewDidLoad();
        
    contentView?.layer.borderWidth = 3.0
    contentView?.layer.borderColor = UIColor(red:102/255,green:102/225,blue:102/225, alpha:1).CGColor
    contentView?.layer.cornerRadius = 14
}
    
And following how it looks.

Friday, June 5, 2015

Hiding status bar in iOS8 using Swift

I recently started learning swift, while learning I started to create simple game. I wanted to make my game full screen, but I was unable to hide top status bar from Interface builder. No matter what I change that status bar was always visible.

Buf I found following code snippet, if you add this code in your View Controller file, you can easily hide status bar.
override func prefersStatusBarHidden() -> Bool {
    return true;
}
Following how my ViewController file looks after adding this code.
class ViewController: UIViewController {
        
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func prefersStatusBarHidden() -> Bool {
        return true;
    }
}
That's it. Hope this will be hopeful.

Sunday, May 3, 2015

Color Animation using Animator with Unity3D

I created a small demo application to demonstrate how Animation can be done using Animator and State Machine with Unity5. This demo creates a Blinking Animation on Mouse click.

Following is final output of this demo.


Below post shows, how above animation can be created.

-> To begin, First create a simple cube and apply a material on the cube. Setup should look like below.

-> Then using "Add Component", add Animator to this cube.

-> Once Animator is added, open Animation window using "Window" -> "Animation", We will need to use while performing the animation.


Animator performs animation using State Machine and this state machine should have default state. Animator will transit to this default State when object is created. In Animator, Animation clip is considered as a State, so lets add a Animation clip and name it default.


-> Our default state will not have any animation, it should show just initial color. Let's just add one frame with current color. Like below.


-> Now we have default state, let's add another state which will perform "Blinking" animation.



-> Now we should add frames, so let's add color property and frames to animate color.




After adding these frames color should animate like below.



-> Now we have Blinking animation state, we are now ready to create a State Machine. Open Animator window by clicking on "Animator" object, it should look like below.

-> We should now add a Parameter which will be used to Trigger animation. On "Animator" window add new boolean parameter and name it "blink".



Following video shows how to create transition and how to add condition to those transition.


-> Now we have state machine with transition and condition, but we want Blink Animation to terminate once its finished. Let's open "Blink Animation" and add Animation event line shown in below image.


This will prompt you to select function to be invoked when Animation frame is reached. You can select function from attached Script.


Following video shows the same process.



-> Finally, We also need to add a script to Cube object. Following is code for the script. In script we are setting "blink" transition parameter of Animator to true on mouse click. While StopAnimation sets "blink" parameter to false when animation event is called.

using UnityEngine;
using System.Collections;

public class MyAnimation : MonoBehaviour {

 private Animator animator;

 void Awake() {
  animator = GetComponent ();
 }

 void OnMouseUp() {
  startAnimation ();
 }

 public void startAnimation() {
  animator.SetBool ("Blink", true);
 }

 public void stopAnimation() {
  animator.SetBool ("Blink", false);
 }
}

And now if run project and click cube, you should see blink animation as per demo video. That's it hope this post will be helpful.

Sunday, April 12, 2015

Handling Drag and Drop with Unity 3D

Drag and Drop is quite useful and we need to implement this quite often in our project. While working on one of my Unity Project, I required to implement the same.

There are some options but I found code described in this post quite simple to use with my project. In this post I will describe how I achieved the same.

So, Let's first create a C# script, I named it Drag.cs and added following code to it. This script will enable touch interaction to added GameObject and will move object along with touch. Also add BoxCollider to GameObject, so we can detect collision.

using UnityEngine;
using System.Collections;
 
public class Drag : MonoBehaviour {
    private Plane plane;
    private Vector3 v3Offset;


    void OnMouseDown() {
 plane.SetNormalAndPosition
             (Camera.main.transform.forward, transform.position);
 Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
 float dist;
 plane.Raycast (ray, out dist);
 v3Offset = transform.position - ray.GetPoint (dist);         
    }

    void OnMouseUp() {
    }

    void OnMouseDrag() {
 Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
 float dist;
 plane.Raycast (ray, out dist);
 Vector3 v3Pos = ray.GetPoint (dist);
 transform.position = v3Pos + v3Offset;  
    }
}
Now, suppose we have another GameObject and we want to detect when GameObject we just created with above script, is dropped on it. To detect drop easily let's first add RigidBody to this GameObject and BoxCollider. After adding BoxCollider also check isTrigger is true. After doing this we need to add C# script to it which will handle drop. Let's name it to Drop.cs and add below code to it.

Below script observe the Collision. When collision happens it checks which object is collided with it. If collided object is Drag object then do something.
using UnityEngine;
using System.Collections;

public class Drop : MonoBehaviour {


    void OnCollisionEnter2D (Collision2D other) {
    }
 
    void OnCollisionExit2D(Collision2D other){
    }
 
    void OnTriggerStay2D (Collider2D other) {
        if( other.gameObject.tag == "Drag" ) {
            // Object dropped, handle the drop
        } 
    }
} 
That's pretty much it, hope this helps.