r/UnityHelp • • Nov 03 '21

PROGRAMMING Coding Terminal Velocity For A 3D Character Controller

Okay, I am making a 3D platformer, and I want to code it so that the character has a terminal velocity, i.e. her maximum fall speed is a set value. I've set gravity at 9.81 m/s^2, or Earthlike, but I want to know how I can set terminal velocity, preferrably around 55 m/s. Here's my code:

  1. using System.Collections;

  2. using System.Collections.Generic;

  3. using UnityEngine;

  4. using UnityEngine.InputSystem;

  5. public class PlayerMovement : MonoBehaviour

  6. {

  7. CharacterController character;

  8. float moveX;

  9. float moveZ;

  10. float moveY;

  11. Vector3 movement;

  12. private Vector3 rotation;

  13. Vector3 velocity;

  14. public float speed;

  15. public float gravity;

  16. public float rotationSpeed = 180;

  17. public float crouchSpeed = 8;

  18. public float jump = 10f;

  19. bool isGrounded;

  20. public Transform groundCheck;

  21. public LayerMask groundMask;

  22. public float groundDistance = 0.2f;

  23. public float highJump = 62.5f;

  24. void Start()

  25. {

  26. character = GetComponent<CharacterController>();

  27. //cameraTransform = Camera.main.transform;

  28. }

  29. void Update()

  30. {

  31. isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

  32. if (isGrounded && velocity.y < 0) {

  33. velocity.y = -2f;

  34. }

  35. this.rotation = new Vector3(0, Input.GetAxisRaw("Horizontal") * rotationSpeed * Time.deltaTime, 0);

  36. Vector3 move = new Vector3(0, 0, Input.GetAxisRaw("Vertical") * Time.deltaTime);

  37. //this.jump = new Vector3(Input.GetAxisRaw("Jump") * jumpSpeed * Time.deltaTime, 0, 0);

  38. move = this.transform.TransformDirection(move);

  39. this.transform.Rotate(this.rotation);

  40. character.Move(move * speed);

  41. //this.transform.TransformDirection(this.jump);

  42. if (Input.GetKey(KeyCode.Z))

  43. {

  44. character.height = .75f;

  45. //character.speed = 8f;

  46. character.Move(move * crouchSpeed);

  47. if (Input.GetButtonDown("Jump") && isGrounded)

  48. {

  49. velocity.y = Mathf.Sqrt(highJump * -2f * gravity);

  50. }

  51. }

  52. else

  53. {

  54. character.height = 1.5f;

  55. //character.speed = 10f;

  56. character.Move(move * speed);

  57. if (Input.GetButtonDown("Jump") && isGrounded)

  58. {

  59. velocity.y = Mathf.Sqrt(jump * -2f * gravity);

  60. }

  61. }

  62. character.Move(movement * speed*Time.deltaTime);

  63. //if (Input.GetButtonDown("Jump") && isGrounded)

  64. //{

  65. //velocity.y = Mathf.Sqrt(jump * -2f * gravity);

  66. //}

  67. velocity.y += gravity * Time.deltaTime;

  68. character.Move(velocity * Time.deltaTime);

  69. }

  70. private void FixedUpdate()

  71. {

  72. }

  73. }

What's the fastest way I can code for terminal velocity?

2 Upvotes

0 comments sorted by