- Home /
Why does my animation repeat? (CSharp)
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour
{
public string jumpButton = "Fire1";
public float jumpPower = 10.0f;
public Animator anim;
public bool grounded = false;
public float minJumpDelay = 0.5f;
public Transform groundCheck;
private float jumpTime = 0.0f;
private bool jumped = false;
// Use this for initialization
void Start ()
{
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update ()
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
jumpTime -= Time.deltaTime;
if(Input.GetButtonDown(jumpButton) && grounded)
{
jumped = true;
grounded = false;
anim.SetTrigger("Jump");
rigidbody2D.AddForce(transform.up*jumpPower);
jumpTime = minJumpDelay;
}
if(grounded && jumpTime <= 0 && jumped)
{
jumped = false;
anim.SetTrigger("Land");
}
if(grounded == false && jumped == false)
{
anim.SetTrigger("Fall");
}
if(grounded)
{
anim.SetTrigger("Fall_Land");
}
}
}
This section here controls when to play my falling animation on my 2D game (unity 4.3) however when my character is falling its all ok but when a land or fall from a ledge it repeats the transition to the fall twice. So it goes from walking animation to falling to walking to falling in the space of a few frames.
if(grounded == false && jumped == false)
{
anim.SetTrigger("Fall");
}
if(grounded)
{
anim.SetTrigger("Fall_Land");
}
Answer by jabez · Dec 02, 2013 at 08:28 PM
Where's grounded == true? by the looks of it, it's always set to false. jump is also always set to false unless you jump, so it will always call this line
if(grounded == false && jumped == false)
{
anim.SetTrigger("Fall");
if I'm wrong don't judge me, I'm fairly new to C#.
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << Layer$$anonymous$$ask.NameToLayer("Ground"));
That is where grounded == true, Assu$$anonymous$$g the linecast returns true.
Thanks for the info! c:, as i said im fairly new. he could try this i wrote for him, probably wont work though, http://pastebin.com/BTb20Tte he has to add a few more if statements but other then that, yeah.
Thanks for all your answers this is my first forum post! I am just trying your script out now.
Hey thanks for the script however it wont seem to work. The problem is when I hit the ground it changes to the right animation then back to the falling then back to the right animation again in a space of two frames.
Your answer
