- Home /
Question by
anglojojo · Nov 11, 2020 at 12:27 AM ·
scripting problemscripting beginner2d animation
Runtime Sprite animation control
Hello,
I've been learning and using Unity for 3 weeks now. I watched some guid about implementing sprite animation via the script rathar than the animator GUI. My problem is that the sprite animation for example "run" keeps playing while I'm off the ground. I've tried using the Y axis input as a condition for the animation, but it didn't work, so I tried to do a ground check and add that as a condition, but its not working for some reason. Any clues?
using UnityEngine;
public class PlayerAnimations : MonoBehaviour
{
Rigidbody2D playerRB;
Animator PlayerAnim;
//Variables to store player movement values
float xAxis;
float yAxis;
bool facingRight;
public bool onGround;
private string currentState; //String variable to store current running animation.
//Animation States
const string PLAYER_IDLE = "PlayerIdle";
const string PLAYER_RUN = "PlayerRun";
const string PLAYER_JUMP = "PlayerJump";
const string PLAYER_FALL = "PlayerFall";
const string PLAYER_LAND = "PlayerLand";
// Start is called before the first frame update
void Start()
{
playerRB = GetComponent<Rigidbody2D>();
PlayerAnim = GetComponent<Animator>();
facingRight = true;
}
// Update is called once per frame
void Update()
{
xAxis = Input.GetAxis("Horizontal");
yAxis = Input.GetAxis("Vertical");
}
void FixedUpdate()
{
if (onGround)
{
if (xAxis != 0)
{
changeAnimationState(PLAYER_RUN);
}
else
{
changeAnimationState(PLAYER_IDLE);
}
}
if (xAxis > 0 && !facingRight || xAxis < 0 && facingRight)
{
facingRight = !facingRight;
playerRB.transform.Rotate(0, 180, 0);
}
}
void changeAnimationState(string newState)
{
if (currentState == newState) return;
PlayerAnim.Play(newState);
currentState = newState;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
onGround = true;
Debug.Log("ON GROUND");
}
}
private void OnCollisionExit2D(Collision2D collision2)
{
if (collision2.gameObject.CompareTag("Ground"))
{
onGround = false;
Debug.Log("not on GROUND");
}
}
}
Comment
Answer by anglojojo · Nov 11, 2020 at 01:43 AM
Update:
I found a way, instead of using getaxis for vertical input, I added a vertical speed variable (velocity.y). Finally, its all kicking into place now.