Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active March 3, 2024 08:30
Show Gist options
  • Save DevEarley/5cc887ec6c05a06959aa24a879bfc1c2 to your computer and use it in GitHub Desktop.
Save DevEarley/5cc887ec6c05a06959aa24a879bfc1c2 to your computer and use it in GitHub Desktop.
Character Motion And Animation script for Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMotionAndAnimation : MonoBehaviour
{
public Animator animator;
public GameObject camera;
public CharacterController controller;
public Vector3 playerVelocity;
private bool groundedPlayer;
private float runSpeed = 5.0f;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private bool isIdle = true;
private float horizontalAxis = 0;
private bool jumping = false;
private bool moving = false;
private bool running = false;
private float verticalAxis = 0;
void FixedUpdate()
{
var forward = camera.transform.forward;
var right = camera.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
var desiredMoveDirection = forward * verticalAxis + right * horizontalAxis;
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = forward * verticalAxis + right * horizontalAxis;
controller.Move(move * Time.deltaTime * (running ? runSpeed : playerSpeed));
moving = move != Vector3.zero;
if (moving)
{
gameObject.transform.forward = move;
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void Update()
{
groundedPlayer = controller.isGrounded;
horizontalAxis = Input.GetAxis("Horizontal");
verticalAxis = Input.GetAxis("Vertical");
running = Input.GetButton("Fire2") == true;
if (jumping == false && groundedPlayer == false && playerVelocity.y <= -3)
{
isIdle = true;
jumping = true;
animator.Play("jump", 0);
}
else if (Input.GetButtonDown("Jump") && groundedPlayer)
{
isIdle = true;
// animator.Play("jump", 0);
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
jumping = true;
animator.Play("jump", 0);
}
else if (jumping && groundedPlayer && playerVelocity.y <= 0)
{
animator.Play("land", 0);
jumping = false;
}
else if (moving && groundedPlayer == true && playerVelocity.y <= 0)
{
if (isIdle == true)
{
isIdle = false;
}
if (running == true)
{
animator.Play("run");
}
else
{
animator.Play("walk");
}
}
else if (isIdle == false && groundedPlayer == true)
{
isIdle = true;
animator.Play("idle");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment