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