UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"create a third person player controller that can walk, sprint, jump and roll. a"
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThirdPersonController : MonoBehaviour { public float walkSpeed = 3f; public float sprintSpeed = 6f; public float jumpHeight = 2f; public float rollSpeed = 5f; private bool isJumping = false; private bool isRolling = false; private Rigidbody rb; private void Start() { rb = GetComponent<Rigidbody>(); } private void Update() { float speed = (Input.GetKey(KeyCode.LeftShift)) ? sprintSpeed : walkSpeed; float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); rb.AddForce(movement * speed); if (Input.GetButtonDown("Jump") && !isJumping) { rb.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse); isJumping = true; } if (Input.GetButtonDown("Roll") && !isRolling) { StartCoroutine(Roll()); } } private IEnumerator Roll() { isRolling = true; float rollTime = 0.5f; float startRollSpeed = rollSpeed; while (rollTime > 0) { rollTime -= Time.deltaTime; rollSpeed *= rollTime / rollTime; yield return null; } rollSpeed = startRollSpeed; isRolling = false; } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Ground")) { isJumping = false; } } }