Sunday 28 December 2014

Catch The Words:

Hi everyone, I have recently worked on a game using Unity 2D. Here is the sample game source files using following features:


  • 2D collision.
  • Text to mesh conversion.
  • Accelerometer for player movement.
  • Co-routines.
  • NGUI basics.
  • Vertical health bar.
  • Lives
 Please play the game download the source code for code.
Link : https://www.dropbox.com/s/t6a3lhplfcdn90p/SKK3.rar?dl=0 

Thank you.


Monday 8 December 2014

Applying force in opposite direction of collision:

After banging my head to each and every script available and possible resource. I came up with the following code  It might help other people with the problem like kicking a football or 8-ball game or etc. The code is for 2D games in Unity, So here it is


public float explosionStrength = 10.0f;
void OnCollisionEnter2D(Collision2D collision) {
Collider2D collider = collision.collider;
 //Debug.Log("Collision with ball "+collider.name);
 if(collider.name == "FootBall")
 { GameObject target_=GameObject.Find("FootBall");
    Debug.Log("Velocity is "+target_.rigidbody2D.velocity.normalized );
    Vector2 forceVec = -target_.rigidbody2D.velocity.normalized * explosionStrength;                  target_.rigidbody2D.AddForce (forceVec, ForceMode2D.Impulse);
    Debug.Log("Collision with ball");
 }

 }

Saturday 19 July 2014

Flappy Bird using Unity

This time I am going to share a tutorial to make a game like "Flappy Bird".  You can download the project from dropbox link or you can go through the following tutorial to get the jist of it.

Lets start by making a 2d Game in untiy 4.x. Follow the tutorial and you will be ready to make a game like this one.

1. Make a 2d project and name it what ever you like,as I named it as Flappy Bird.

2. Second step is very important always I am repeating it always organize your projects it helps in any kind of modification. So make new folders as Prefabs, Scenes, Scripts and Textures. We will add more folders if required. So go and make folders.

3. First of all look for a wallpaper for you game. Do not judge mine as it was a random pick haha. So lets move forward - Copy the image into textures folder and drag it to the screen area(Scale it to fit the screen in my case it is x=2.4 and y=1.4)

4. Now it's time to make our bird goto google and search anything like "flappy bird png" , "flappy bird tga" or "flappy bird texture" you will surely find something of use, Copy the image to the textures folder and drag that one too to the scene. My image is hi-res that is why I have scaled it down. Name it as "Bird"(We are not using any sprite sheet because purpose of the tutorial is somewhat different I will cover that part in some other tutorial).

5. Lets add some physics to our game, add the component "Rigidbody 2D" to the "Bird". Save the scene in Scenes folder and press play and it should fall.

6. Lets make the jump script. Make a new C# script in Scripts folder and name it as Jump. Code is as follows

using UnityEngine;
using System.Collections;
 public class Jump : MonoBehaviour {
 // Use this for initialization 

 public Rigidbody2D bird;

  void Start () { 
 } 

//Update is called once per frame

  void Update () { 
         if(Input.GetKeyUp("space")) 
         {        bird.velocity=Vector2.zero;
                  bird.AddForce(new Vector2(0,250)); 
         } 
  } 


Script is easy to understand it checks for the input. Once it get the input it will turn the velocity of our "Bird" to zero and add the upward force for jump.
Make an empty Gameobject name it what ever you like and attach the script to it or you can attach the script to the main camera(I have used the later approach). At last add the "Bird" gameobject to the instance if the script.

7.Next part is making obstacles for the game. Search something like "mario pipe png" in google images you will find the obstacles. Create an empty Game object in the editor. Name it as "Obstacles pair" drag the png you just downloaded to the textures folder. Now add it 2 time to your scene. Make them children of "Obstacles pair" name one as "obstacle1" and other as "obstacle2". Now final step is rotating the obstacle. In my case I had to give "obstacle1" rotation of 180 degrees at z axis. And you should give the distance of your bird+0.3 (or more) between your obstacles so that bird can pass between them. Your game should look like this


8. Now you have to attach a rigidbody to the obstacles so that you can give it some velocity. Now here are the actions you have to take to complete this phase.

  • add a component of "Rigidbody2D" to the parent object and mark it as "is Kinematic". Anything which is marked as "is Kinematic" will stop responding to gravity.

    •   }

      // Update is called once per frame
      void Update () {

        }
      }
  • Create a new C# script in your scripts folder and name it as "MoveObstacle". Code is given below
    using UnityEngine;
    using System.Collections;
    public class MoveObstacle : MonoBehaviour {
    public Vector2 velocity = new Vector2(-3, 0);
    // Use this for initialization
    void Start () {
    rigidbody2D.velocity=velocity; }

    // Update is called once per frame
    void Update () {

      }
    }
  • Script is self explanatory you make a new velocity variable and apply that velocity to obstacle pair gameobject. As it is not a sidescoller game so we don't have to move environment and player we just have to move obstacles. Apply this script to "Obstacles pair" gameobject.
9.  We have to generate obstacles every few seconds.
  • First of all make an empty prefab name it as "ObstaclesPair".
  • Drag the "Obstacles pair" gameobject from the scene onto it.
  • Now make a new C# script named as "GenerateObstacle" in Scripts folder and attach it to Main Camera as it will generate obstacles with the passage of time. Bode is below(I am not showing randomness in heights as its your work to do :D )
  • using UnityEngine;
    public class GenerateObstacle : MonoBehaviour
    {
    public GameObject obstales;
    public bool gen=true;
    public float seconds=0;
    public int updateCounter=0;
    public int maxRange=170;
    // Use this for initialization
    void Start()
    {
    }
    void Update()
    {

    if(gen)
    {
     gen=false;

     Invoke("GenerateNewObstacle" , Random.Range(4,8));
    }
    else
     updateCounter++;
     if(updateCounter >= maxRange)
    {
     gen=true;
     updateCounter=0;
    }
    }
    void GenerateNewObstacle()
    {
      Instantiate(obstales);
    }}

10. So now the turn is of killing the player. There could be 2 reasons for it either Bird has touched the ground or sky or it has collided with obstacle. Following are the steps the implement these features
    • Apply Box collider 2D to the Bird gameobject.
    • Appy polygon collider 2D to the both of obstacles and update your Prefab for obstacles.
    • on collision of birds Restart the level.
    11. Download the project to see how does all of it works.

    Sunday 29 June 2014

    Penalty shoot-out using Unity3D

    Hi

    I have made this game prototype on the weekend . Kindly let me know if you think it needs other modification.





    It basically works without gravity and new ball is spawned on the same position once it is is kicked using a gesture. I know it's a rough one but it can convey the gist of the project. :)

    Here you can download the project : Link

    Wednesday 18 June 2014

    Sniper shooter Part 2

    Sniper shooter prototype part 2:

    Lets set up cameras for the game. We need two cameras for the gun after setting them up we will add the cameras to the gun prefab so that it can be reused easily. Follow the steps for this purpose

    • Download the following textures of crosshair for normal and zoom camera 



    Normal cam crosshair

    Zoom cam crosshair


    • Make an empty game object in your scene name it as player or whatever you like.
    • Make GunsAndHands prefab child of this gameobject you created and change its position to (0,0.7297325,0).
    • Now make another empty gameobject in the scene (name it cameras) make this gameobject child of "player" gameobject then change its position vector to (0,1,0)
    • Create a camera gameobject in the scene name it as MainCamera change the tag of this gameobject to "MainCamera"(you will have to create a new tag) with the following settings



    • Make the MainCamera gameobject child of "cameras" and change its position  to (0,-0.177351,0)
    • Now the next camera will be of zoom so it will a have a lesser Field of view(FOV)
      and more far clipping than main camera so create a new camera with the following settings and name it as ZoomCamera with the following settings
    • Make ZoomCamera child of cameras and change its position to (0.3755417 , -0.2398739 , 3.198844)
    • Now its time to putcrosshairs in place. We have to put transparent planes in front of cameras and then apply the textures. As plane available in unity is not transparent and it consists of lot of vertice so here I have a custom plane for this purpose. You can download the project and find how crosshairs work.
    So this is how our game should look like by now


    You can download the unity package from here  (PlayerPrefab is the updated one)

    Tuesday 17 June 2014

    Sniper Shooting prototype (Part 1)

    Hi,

    First of all what we need is a Sniper gun model (.fbx format) with the animation like


    • idle
    • walk
    • reload
    So as I know that most of the game devs are not in to the 3D asset development so I am going to share the model of gun in this post. We will use the First person camera view with model (animations are included in the unity package).

    Please download the package, drag the gun into your scene and see how the animations works. The motion which makes the sniper gun move little bit in and out of the axis because of wind pressure is part of idle animation so, it will help in making game little more interesting. (I have not made this model so we must thanks the random guy over who has shared it over the internet)

    You can download from here


    Monday 16 June 2014

    Sniper prototype using Unity 3D

    I have read it many times on internet people asking for tutorial on sniper game . I will be sharing tutorials to make a basic sniper shooting game. I hope it will be a fun project.

    2d Platformer in Unity 3D

    Among the first few games that I developed using Unity 3D was this 2d platformer(using Unity Development by Jate Wittayabundit). I made it in 2011 for learning purpose.

    Here are the screenshots




    It is a simple one level platformer prototype you can download the project from here

    Sunday 15 June 2014

    FPS in progress

    Hi everyone,

    I have been working on a multiplayer FPS for handheld devices lately. Its a personal project . I am making it using unity 3D and photon cloud.
    Here are the screenshots





    Androdi Instagram integration

    I needed to integrate instagram with android app. As there is no instagram api available for android so you have to integrate it using oauth(using access token). At that time I wasn't able to find any help regarding the instagram integration. So I am sharing the project.

    You can find the project here : download link

    Space invaders in opengl

    Hi readers,

    In one of the tests I was assigned to make a space invaders like game in c++ and opengl.( You will need glut to run the assignment). I have uploaded my assignment on dropbox. May be it can help someone searching for the same thing. :)

    You can download the project from here : dropbox link

    Sunday 2 February 2014

    Side scroller:

    The basic sciene in a side scroller game is animation controller. You have to move character only in one dimenstion except when the character is jumping. I will sharing the animation controller script and project in this post.
    #pragma strict

    var normalSpeed:float=6.0;
    private var speed:float=normalSpeed;
    var runSpeed:float=12;
    private var jumpSpeed:float=speed*1.7;
    var gravity:float=20;
    private var walkTime:int=0;
    private var moveDirection:Vector3=Vector3.zero;
    static var grounded=false;
    private var controller:CharacterController;
    private var flags:CollisionFlags;
    var targetRotation:int=90;

    function Start () {

    animation.wrapMode=WrapMode.Loop;
    animation["run"].layer=-1;
    animation["walk"].layer=-1;
    animation["idle"].layer=-1;
    animation.SyncLayer(-1);

    animation["jump"].layer=10;
    animation["jump"].wrapMode=WrapMode.Once;
    animation.SyncLayer(10);
    animation.Stop();
    animation.Play("idle");
    }


    function FixedUpdate()
    {
    if(grounded)
    {
    moveDirection=new Vector3(Input.GetAxis("Horizontal"),0,0);
    moveDirection*=speed;
    if(Input.GetButton("Jump"))
    {
    moveDirection.y=jumpSpeed*2;
    animation.CrossFade("jump");
    }
    }
    moveDirection.y-=gravity* Time.deltaTime;
    controller=GetComponent(CharacterController);
    flags=controller.Move(moveDirection*Time.deltaTime);

    grounded= (flags & CollisionFlags.CollidedBelow)!=0;

    if(moveDirection.x>0)
    targetRotation=90;
    else if(moveDirection.x<0)
    targetRotation=270;

    transform.eulerAngles.y-=(transform.eulerAngles.y-targetRotation)/5;

    Debug.Log("Grounded " + grounded);
    if(Input.GetAxis("Horizontal")>0.1 || Input.GetAxis("Horizontal")<-0.1)
    {
    if(walkTime<-2)
    {

    animation.CrossFade("run");
    speed=runSpeed;
    }
    else{

    //Debug.Log("Walk anim");
    walkTime++;
    animation.CrossFade("walk");
    speed=normalSpeed;
    }
    jumpSpeed=speed*1.7;
    }
    else
    {
    walkTime=0;
    animation.CrossFade("idle");
    }
    }


    function Update () {

    }


    @script RequireComponent(CharacterController)


    so this is the basic code. There is nothing special going around in code I think it is easy to understand.

    Here is the link for the unity project: https://db.tt/tszcEjpu

    Thank you

    Tuesday 28 January 2014

    Endless Runner(Part 2)


    Ok time to get your hands dirty with code. In game we will have small class to represent cell properties.We will be doing most of the code in one script(Using JS). Lastly I am not saying it is the best approach which I will share, this is what I know there could be better other solutions too.

    Create a new JS script name it GameController . First of all we will declare few enumeration type variables for representing directions and type of cell.


    enum direction { N, E, W, S, NS, EW}
    enum cellType {run,jump,jumpObstacle,duck,left,right}


    now create an inner class in GameController name it "CellProperties".  It will hold the information about the cell that will be displayed on screen. The member variables in class will be position,dir,type,model,neighbours,coins,spikes and visited bool.

    class CellProperties

    {

    var position:Vector3;
    var dir:direction;
    var type:cellType;
    var model:GameObject;

    var neighbourN:CellProperties;
        var neighbourE:CellProperties;
        var neighbourW:CellProperties;
        var neighbourS:CellProperties;
        var visited=false;
        var coins = new ArrayList();
        var spikes = new ArrayList();
        
        function setValues( cPosition:Vector3,  cDir:direction, cType:cellType)
        {
       
        this.position  = cPosition;
    this.dir = cDir;
    this.type = cType;
    this.neighbourN = null;
    this.neighbourE = null;
    this.neighbourW = null;
    this.neighbourS = null;
        }

    };

    This is the structure of cell class. In next part I will setup the scene and make the prefebs for the cells. 
    Thank you.

    Here you can find the source code : https://dl.dropboxusercontent.com/u/79608708/CellClass.js

    Monday 27 January 2014

    Endless Runner (Part1):

    Ok so lets start with runner game as mentioned in last post. Here is the basic intro for such kind of game.


    • You need to decide camera view.
    • You need an algo to create path dynamically 
    • You need to decide obstacles.
    • You need to decide animations/actions of player e.g run,jump,slide down etc.
    For character animations download the max character from unity asset store it is free (https://www.assetstore.unity3d.com/#/content/3012)

    The most interesting part would be creating path dynamically. Roughly it would be like you will show specific number of cells/bridges/steps on screen let suppose the number is 10. Now you will track the index of cell on which the player is present. If it is more than 5 you create next 10 cells on screen and delete the 5 cells that are behind the player. In this way you will keep on creating endless path.

    I will start posting the code and screenshots from the next post.I hope readers have the  basic understanding of Unity and scripting in C# and JS.
    Meanwhile you can update me regarding your queries.

    Thank you.
    Before getting into any kind of field one should get familiarized with jargon of respective area. Here is a great source for learning basic terminologies of game dev.

    http://en.wikipedia.org/wiki/User:Jreynaga/Books/3D_Graphics_Terms

    Thank you.
    I will be sharing small tutorials regarding game dev in unity in this blog. You can reach me out anytime by dropping an email at h.hassanalikhan@gmail.com

    My first game tutorial series would be based on endless runner theme.

    Thank you.