Question by
andrewwebber25 · May 20, 2017 at 09:19 AM ·
animationanimatoranimator controllerplayer movementwalking
How do I apply an animation to a sprite?
Basically I have the player move left and right when you press the left and right arrows on the keyboard / phone screen. Ive created a walking animation for the player that I would now like to apply. How do I do this is my script code so that when the user holds down the right arrow, the animation will play? The animation is named "PlayerWalk" and I made a trigger called "Walk". I know this is a total noob question but I could really use some help. Thanks everyone!
using UnityEngine;
using System.Collections;
public class Controls : MonoBehaviour
{
public Rigidbody2D rb;
public float movespeed;
public float jumpheight;
public bool moveright;
public bool moveleft;
public bool jump;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
rb.velocity = new Vector2(-movespeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.RightArrow))
{
rb.velocity = new Vector2(movespeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.Space))
{
if (onGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpheight);
}
}
if (jump)
{
if (onGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpheight);
}
jump = false;
}
if (moveright)
{
rb.velocity = new Vector2(movespeed, rb.velocity.y);
}
if (moveleft)
{
rb.velocity = new Vector2(-movespeed, rb.velocity.y);
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612122214im_/https://answers.unity.com/themes/thub/images/avi.jpg)