Question by
unity_WAsXmOs-rROT3Q · Jun 13, 2020 at 07:37 PM ·
c#animationbeginner
Beginner trying to add animation
I'm still a beginner at this coding thing, so I ran into a mental bump. So, I am working on a 2D platformer. I am trying to get my player character to play a running animation when he moves left and right (across x axis). I got the idle and jumping animations to work fine. It's just I'm confused as to how to implement the running animation in my code... noob ikr haha.
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
Animator animator;
public Rigidbody2D rb;
SpriteRenderer spriterenderer;
public float jumpForce = 20f;
public float runspeed = 20f;
public Vector2 jumping;
private bool isGrounded;
[SerializeField]
Transform groundCheck;
Vector3 characterScale;
float characterScaleX;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
spriterenderer = GetComponent<SpriteRenderer>();
characterScale = transform.localScale;
characterScaleX = characterScale.x;
}
// Update is called once per frame
void Update()
{
// jumping---
// this new vector makes it to where jumping is
// 5x as strong in y as x
jumping = new Vector2(1, 5);
if (Input.GetButtonDown("Jump") && isGrounded)
{
//adds a force upwards (jump)
rb.AddForce(jumping, ForceMode2D.Impulse);
animator.Play("player-jump");
}
else
{
if (!isGrounded)
{
animator.Play("player-jump");
}
}
if (Input.GetAxis("Horizontal") < 0)
{
characterScale.x = -characterScaleX;
}
if (Input.GetAxis("Horizontal") > 0)
{
characterScale.x = characterScaleX;
}
transform.localScale = characterScale;
}
void FixedUpdate()
{
//linecast for jumping and ground check
if (Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("ground")))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
//player movement
Vector2 playerInput;
playerInput = new Vector2(Input.GetAxis("Horizontal") * runspeed * Time.deltaTime, rb.velocity.y);
rb.velocity = playerInput;
if (isGrounded)
{
animator.Play("player-idle");
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613000842im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
AnimationComplete() Error 0 Answers
How to play all the animations array inside animation component 0 Answers
Free Look Camera Rig Changing Rotation 1 Answer
Use a string to call a class 2 Answers
Check for collision while animating 0 Answers