unity – Determine when a character is stationary, and which direction they are facing


I’m currently trying to figure out two things for my character’s movement and animation.

  1. A better/faster way to track when movement stops than the IsSleeping method.
  2. A way to track which direction my character is facing to send this information to the animator.

Here is the code I’m currently using for movement and sending information to the animator:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KittenController2 : MonoBehaviour
{
    Rigidbody2D rb;
    Animator ani;

    public float speed;
    public float jumpForce;

    private float direction = 0f;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        ani = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        direction = Input.GetAxis("Horizontal");
        ani.SetBool("Stationary", rb.IsSleeping());
        
        if (direction > 0f)
        {
            rb.velocity = new Vector2(direction * speed, rb.velocity.y);
            ani.SetFloat("Move X", direction);
        }
        else if (direction < 0f)
        {
            rb.velocity = new Vector2(direction * speed, rb.velocity.y);
            ani.SetFloat("Move X", direction);
        }
        else
        {
            rb.velocity = new Vector2(0, rb.velocity.y);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    void FixedUpdate()
    {

    }

    void Jump()
    {
        rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
        ani.SetTrigger("Jump");
    }
}



Source link

More To Explore

A.M.A. Short Film UI Exploration

Objective: Create a self-driven car UI for a fictional ride-sharing company for a short film A.M.A. The direction was to create an AI that was

Share on facebook
Share on twitter
Share on linkedin
Share on email