- Home /
The question is answered, right answer was accepted
Walking and Running Script not working.
Hey, I tried to make a script where if I click/hold "w" the character would walk and if I click/hold "w" and "leftShift" at the same time he would sprint. Any help is appreciated. He walks fine but when I try to sprint he just preforms the walk animation. Here is my script:
#pragma strict
var ArmsWalkingForward : AnimationClip;
var SprintAnimation : AnimationClip;
var IsWalking : boolean = false;
var IsSprinting : boolean = false;
function Start ()
{
}
function Update ()
{
if(Input.GetKeyDown(KeyCode.W) && !IsSprinting)
{
IsWalking = true;
}
if(Input.GetKeyUp(KeyCode.W) && !IsSprinting)
{
IsWalking = false;
}
if(Input.GetKeyDown(KeyCode.W) && Input.GetKeyDown(KeyCode.LeftShift) && !IsWalking)
{
IsSprinting = true;
}
if(Input.GetKeyUp(KeyCode.W) && Input.GetKeyDown(KeyCode.LeftShift) && !IsWalking)
{
IsSprinting = false;
}
//Actions
if(IsSprinting == true)
{
Sprint();
}
if(IsWalking == true)
{
Walk();
}
}
function Sprint()
{
animation.Play("SprintAnimation");
}
function Walk()
{
animation.Play("ArmsWalkingForward");
}
He walks fine but when i try sprint he just performs the walk animation.
Answer by Mmmpies · Mar 01, 2015 at 09:26 AM
You just the logic wrong, try this:
#pragma strict
var ArmsWalkingForward : AnimationClip;
var SprintAnimation : AnimationClip;
var IsWalking : boolean = false;
var IsSprinting : boolean = false;
function Start ()
{
}
function Update ()
{
if(Input.GetKeyDown(KeyCode.W))
{
IsWalking = true;
}
if(Input.GetKeyUp(KeyCode.W))
{
IsWalking = false;
}
if(Input.GetKeyDown(KeyCode.LeftShift))
{
IsSprinting = true;
}
if(Input.GetKeyUp(KeyCode.LeftShift))
{
IsSprinting = false;
}
//Actions
if(IsSprinting == true && IsWalking == true)
{
Sprint();
}
if(IsWalking == true && !IsSprinting)
{
Walk();
}
}
function Sprint()
{
animation.Play("SprintAnimation");
}
function Walk()
{
animation.Play("ArmsWalkingForward");
}
Thank you almost working perfectly the only problem is he doesn't stop walking.
O$$anonymous$$ I didn't have your animations so when I tested it I just Debug.Log to show walking or sprinting. It stops calling the Sprint or Walk but you've got no function to stop the animation so something like this:
// In update
if(!IsWalking)
{
Idle();
}
// then
function Idle()
{
animation.Play("Idle");
}
Assu$$anonymous$$g you have an idle animation called Idle.