Sunday, June 29, 2014

Texture Fadein Fadeout using Coroutine - Unity3d

Code for making fadein, fadeout in Unity3d C#,


Fadein,

IEnumerator FadeIn(GameObject gameObj)
 {
  for (float f = 0f; f <= 1; f += 0.01f)
  {
   Color c = gameObj.renderer.material.color;
   c.a = f;
   gameObj.renderer.material.color = c;
   yield return new WaitForSeconds(.01f);
  }

  yield return null;
 }

Fadeout, 

IEnumerator FadeOut(GameObject gameObj)
 {
  for (float f = 1f; f >= 0; f -= 0.01f)
  {
   Color c = gameObj.renderer.material.color;
   c.a = f;
   gameObj.renderer.material.color = c;
   yield return new WaitForSeconds(.01f);
  }

  yield return null;
 }

Pre Requisites: Object you are passing  as argument must have shader which has color property in it.

FadeInFadeOut using NGUI UISprite and Coroutine,


 public UIAtlas RunTimeAtlas;

IEnumerator ColorFadeInFadeOut() 
{
UISprite newSprite = NGUITools.AddWidget<UISprite>(GameObject.Find("Story"));
newSprite.depth = 6;
newSprite.gameObject.name = "FadeInFadeOut";
newSprite.atlas = RunTimeAtlas;
newSprite.spriteName = "White120";
newSprite.SetDimensions (Screen.width * 3, Screen.height * 3);
TweenAlpha ta1 = newSprite.gameObject.AddComponent<TweenAlpha> ();
ta1.from = 0.0f;
ta1.to = 1.0f;
yield return new WaitForSeconds(1.10f);
TweenAlpha ta2 = newSprite.gameObject.AddComponent<TweenAlpha> ();
ta2.from = 1.0f;
ta2.to = 0.0f;
yield return new WaitForSeconds(1.0f);
NGUITools.Destroy(newSprite.gameObject);
}

Pre Requisites: Atlas reference must be assigned to RunTimeAtlas in Unity Inspector having white texture in it. Texture of other color can also be used for fade in and fade out effect.

Monday, June 23, 2014

Camera and Texture settings to make 2d game in Unity

Here are some basic Camera and Texture setting for 2d game development in Unity3d,


(1). Choose 'Point' as the filter mode for your textures.
(This is essential for making your textures sharp).

(2). Choose 'Advanced' as your 'Texture Type' and disable 'Generate Mip Maps'.
(This is also important for 2d game, it reduces texture size as well).

(3). Choose 'RGBA 32 bit' as your 'Texture Format'.
(Choose lesser until your texture quality remains, this is also for texture memory size).

(4). Set your Camera Projection to 'Orthographic'.
(To make game for 2d view only).

(5). Set your 'Orthographic Size' to your screen height / 2.
(This makes 1 unit in Unity equals 1 pixel on your textures).

(6). Create a Quad by following Menu -> GameObject -> Create Other -> Quad in Unity.

(7). Scale your Quad to same size as your texture.
(A 256*256 texture needs a 256*256 quad).

Note : Textures you are using must be POT(Power Of Two) textures.

Code snippets to set Camera size,


using UnityEngine;


public class 2dCameraScale: MonoBehaviour 
{
    void Awake () 
    {
        Camera.main.orthographicSize = Screen.height / 2;
    }
}

Post Note : The topic is posted for Unity3d v. 4.2.1 or older mainly, in newer versions their are lots of 2d related stuffs are added. Though you can use above settings for newer version also. ;)

Texture tiling with NPOT texture Unity3d

Thought NPOT(Non Power Of Two) textures are not advisable to use in Unity3d, but if you are using it then one important thing to note down here is that NPOT texture doesn't support Repeat Wrap Mode. If you are trying to used Repeat Wrap Mode with NPOT texture then it might result in improper tiling of a texture.

Wednesday, June 18, 2014

Show key/value pair in Unity3d Inspector

           By default Unity doesn't serialize Dictionary, So it is not possible to show key/value pair directly in Unity3d inspector. But this can be achieved using some simple tweaks shown below,

using UnityEngine;
using System.Collections;

[System.Serializable]
public class SoundManager : MonoBehaviour


public class AudioClip_Dir_Class
{
  public string audioClipName;
  public AudioClip audioClipvalue;
}

{
  public AudioClip_Dir_Class []audioClip_Dir;
}

Alternatively you can also go with below one,

public List<string> keys = new List<string>();
public List<MyClass> values = new List<MyClass>();
private Dictionary<string,MyClass> dict;

Tuesday, June 17, 2014

Texture compression and Optimization Unity3d

Always use Textures(for 3D only) in the power of Two(POT).
Because PVRTC only compress an image if it is in POT.
RGBA images are not compressed in iOS and they are saved without compressing. So it is preferable to use textures in the POT if it is texture of 3D model.

2D games shouldn't use compression at all, as the compression mess up with the alpha, which will cause semi transparent areas to look horrible.

To make 2D sprites, RGBA 32 Bit or 16 Bit texture is preferable for best graphics quality.

Games Must Have..

         Here three basic things Game Must Have to engage user and make impression in game market.


1. Nice concept

        This is where game development journey starts - A Good Concept. Game must have nice concept to stick user with game. One best example of this is very famous game Flappy Bird - A simple yet addictive game.


2. Eye catching graphics and User Interface(UI)

         As far as Game development concerns game must have nice, attractive graphics so that it would make very good impression on first see. Nice graphics are also very useful in marketing point of view. This is where simple rule works - "That which is seen is Sold".


3. Animations

        Yes it should be full of animations, Wait wait wait, let me make it clear this term.
        Here point of talk is, it should be full of Sprites(image sequences) for 2d games and animated/movable UI's for better user experience. Best example for this is Farm Heros Saga - A fun playing, entertaining game with full of animations.

        There are also other things like Particle Effects, Sounds etc. Which are also playing a role to make user experience better and too rock the game market.

Sunday, June 15, 2014

Factors affected and not affected by Time.timeScale

List of factors affected by Time.timeScale,


1. Coroutines
2. Invokes and InvokeRepeating
3. All physics related simulations (FixedUpdate())
4. Animations
5. Particle System

    To make it working, timeScale must be great than 0.0f. It would work even if it is set to 0.001f, Thought to run it on normal repeating rate, you should go for some short of simple logic,

For instance,
    If you want to work Animation even after timeScale is set to 0.001f, you should set animation speed to 0.001f / Time.timeScale. So it will go with regular frame rate.


List of factors doesn't affected by Time.timeScale,


1. Update()
    Time.timeScale will not make any affect on Update call, it will invoked as per the frame rate until and unless it is not used in any statement for computation.

For example,
float distance = Time.timeScale * 10.0f;
transform.Translate (0, 0, distance); 

will make affect on movement as Time.timeScale is being used while making object movement. It is moving object 10m/second.


while,
float distance = 10.0f;
transform.Translate (0, 0, distance); 

will not make any affect of timeScale on object movement and moving object  10m/frame instead.


2. OnGUI()
    OnGUI and its event have overlaying architecture over Time.timeScale, so it won't be affected if it goes to lower or set to 0.


Also see,

Saturday, June 14, 2014

Camera Shake J# Unity3d

var camera : Camera;
var shake : float = 0;
var shakeAmount : float = 0.7;
var decreaseFactor : float = 1.0;

function Update() 
{
  if (shake > 0) 
  {
    Camera.transform.localPosition = Random.insideUnitSphere * shakeAmount;
    shake -= Time.deltaTime * decreaseFactor;
  } 
  else 
  {
    shake = 0.0;
  }
}

Camera Shake C# Unity3d

using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { public Transform camTransform; public float shake = 0f; public float shakeAmount = 0.7f; public float decreaseFactor = 1.0f; Vector3 originalPos; void Awake() { if (camTransform == null) { camTransform = GetComponent(typeof(Transform)) as Transform; } } void OnEnable() { originalPos = camTransform.localPosition; } void Update() { if (shake > 0) { camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount; shake -= Time.deltaTime * decreaseFactor; } else { shake = 0f; camTransform.localPosition = originalPos; } } }

Thursday, June 12, 2014

Time.timeScale and iTween ignoretimescale property

iTween property "ignoretimescale" doesn't work if it is used along with "delay" property withing same function.

For instance

iTween.MoveTo(gameObject,iTween.Hash("x", .25, "easetype", iTween.EaseType.easeInSine, "time", .2, "ignoretimescale", true, "delay", .2));

would be affected by Unity3d timeScale even though "ignoretimescale" property is used in it,

while,

iTween.MoveTo(gameObject,iTween.Hash("x", .25, "easetype", iTween.EaseType.easeInSine, "time", .2, "ignoretimescale", true));


will ignore Unity3d timeScale and "ignoretimescale" will function properly.

More important about Time.timeScale,

Best Practice for Game Development!

Unity3d C# Code to Convert Screen Size to World Co-ordinates

C# code to convert screen size to world co-ordinates,

Vector2 GetScreenSizeInWorldCoords()
{
   Camera cam = Camera.main;
   Vector3 p1 = cam.ViewportToWorldPoint(new Vector3(0,0,cam.nearClipPlane));
   Vector3 p2 = cam.ViewportToWorldPoint(new Vector3(1,0,cam.nearClipPlane));
   Vector3 p3 = cam.ViewportToWorldPoint(new Vector3(1,1,cam.nearClipPlane));

   float width = (p2 - p1).magnitude;
   float height = (p3 - p2).magnitude;

   Vector2 dimensions = new Vector2(width,height);

   return dimensions;
}

Coroutines and Time.timeScale

           Most important thing need to keep in mind while using Coroutine is that, Coroutine is affected by Timescale.
           
           When time scale is reduces to 0 then Coroutine won't be called. This is the different behavior then MonoBehaviour Update() call which is still getting invoked even after Timescale reduced to 0.


More notes about Time.timeScale,

Best Practice for Game Development!

Game Programming Prerequisites

Basic things should be with you for game development,


Artificial Intelligence

  • Finite State Machine
  • Fuzzy Logic
  • Behaviour Trees
  • Path Finding
  • Steering Behaviors

Game Play Mechanics

  • Input
  • Camera Movement
  • Animation Mixing
  • Particle Effects
  • UI and Tweening
  • Sound

Maths

  • Algebra and Arithmetic
         These are pretty basic, but if you don't know these you won't have a chance at even being a programmer let alone a game developer.

  • Vector Math


         Objects in a game world represented with vectors. Vector math calculations suck as the Dot Product, Cross Product, Vector Normalization are essential.

    Physics

             Physics is also must for being game developer. One can go with game development without use of physics but it is essential to be quite familiar with physics.

              Are you a Game Developer or planning to being a game developer ? here are the important tips for you,


    Best practice for game development!

    Popular Posts