0% found this document useful (0 votes)
3 views

Controller

The PlayerController script in Unity manages player movement, including walking, running, and jumping mechanics. It utilizes Rigidbody for physics interactions and Animator for character animations based on player input. The script also incorporates a stamina system that affects running speed and regenerates over time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Controller

The PlayerController script in Unity manages player movement, including walking, running, and jumping mechanics. It utilizes Rigidbody for physics interactions and Animator for character animations based on player input. The script also incorporates a stamina system that affects running speed and regenerates over time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using UnityEngine;

using TMPro;

public class PlayerController : MonoBehaviour


{
[SerializeField] float movementSpeed = 5f;

float currentSpeed;

[SerializeField] Rigidbody rb;


Vector3 direction;

[SerializeField] float shiftSpeed = 10f;


[SerializeField] float jumpForce = 7f;
[SerializeField] float stamina = 5f;

bool isGrounded = true;

[SerializeField] Animator anim;


void Start()
{
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
currentSpeed = movementSpeed;
}

void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

direction = new Vector3(moveHorizontal, 0.0f, moveVertical);


direction = transform.TransformDirection(direction);
if(direction.x != 0 || direction.z != 0)
{
anim.SetBool("Run", true);
}
if(direction.x == 0 && direction.z == 0)
{
anim.SetBool("Run", false);
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(new Vector3(0, jumpForce, 0), ForceMode.Impulse);
isGrounded = false;
anim.SetBool("Jump", true);
}
if(Input.GetKey(KeyCode.LeftShift))
{
if(stamina > 0)
{
stamina -= Time.deltaTime;
currentSpeed = shiftSpeed;
}
else
{
currentSpeed = movementSpeed;
}
}
else if (!Input.GetKey(KeyCode.LeftShift))
{
stamina += Time.deltaTime;
currentSpeed = movementSpeed;
}
if(stamina > 5)
{
stamina = 5;
}
else if (stamina < 0)
{
stamina = 0;
}

print(stamina);
}

void FixedUpdate()
{
rb.MovePosition(transform.position + direction * currentSpeed *
Time.deltaTime);
}
void OnCollisionEnter(Collision collision)
{
isGrounded = true;
anim.SetBool("Jump", false);
}
}

You might also like