| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- public Rigidbody rb;
- public float walkSpeed = 5f;
- public float runSpeed = 10f;
- public float rotateSpeed = 100f;
- public float jumpForce = 50f;
- public float stamina = 100f;
- public float drainRate = 20f;
- public bool bIsSprinting;
- public bool bCanSprint;
- public int health;
- public bool bHasBeenDamaged;
- private float currentSpeed;
- private bool bIsGrounded;
- private Vector2 input;
- void Update()
- {
- input.x = Input.GetAxis("Horizontal");
- input.y = Input.GetAxis("Vertical");
- bIsSprinting = Input.GetKey(KeyCode.LeftShift) && input.y > 0 && bCanSprint;
- currentSpeed = bIsSprinting ? runSpeed : walkSpeed;
- if (bIsSprinting)
- {
- stamina -= drainRate * Time.deltaTime;
- }
- stamina = Mathf.Clamp(stamina, 0, 100f);
- if (Input.GetButtonDown("Jump") && bIsGrounded)
- {
- Jump();
- }
- /*if (Input.GetKeyDown(KeyCode.F5))
- {
- GameManager.gameManagerInstance.SaveData();
- }*/
- }
- private void FixedUpdate()
- {
- Vector3 moveDirection = transform.forward * input.y * currentSpeed;
- rb.linearVelocity = new Vector3(moveDirection.x, rb.linearVelocity.y, moveDirection.z);
- float rotation = input.x * rotateSpeed * Time.fixedDeltaTime;
- transform.Rotate(0, rotation, 0);
- }
- private void Jump()
- {
- rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
- bIsGrounded = false;
- }
- public void ReduceHealth()
- {
- bHasBeenDamaged = true;
- health--;
- if(health <= 0)
- {
- Debug.Log("Player is dead");
- bHasBeenDamaged = false;
- }
- bHasBeenDamaged = false;
- }
- private void OnCollisionStay(Collision collision)
- {
- foreach (ContactPoint contact in collision.contacts)
- {
- if (contact.normal.y > 0.7f)
- {
- bIsGrounded = true;
- break;
- }
- }
- }
- private void OnCollisionExit(Collision collision)
- {
- bIsGrounded = false;
- }
- }
|