r/UnityHelp • u/Fantastic_Year9607 • 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:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
CharacterController character;
float moveX;
float moveZ;
float moveY;
Vector3 movement;
private Vector3 rotation;
Vector3 velocity;
public float speed;
public float gravity;
public float rotationSpeed = 180;
public float crouchSpeed = 8;
public float jump = 10f;
bool isGrounded;
public Transform groundCheck;
public LayerMask groundMask;
public float groundDistance = 0.2f;
public float highJump = 62.5f;
void Start()
{
character = GetComponent<CharacterController>();
//cameraTransform = Camera.main.transform;
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
this.rotation = new Vector3(0, Input.GetAxisRaw("Horizontal") * rotationSpeed * Time.deltaTime, 0);
Vector3 move = new Vector3(0, 0, Input.GetAxisRaw("Vertical") * Time.deltaTime);
//this.jump = new Vector3(Input.GetAxisRaw("Jump") * jumpSpeed * Time.deltaTime, 0, 0);
move = this.transform.TransformDirection(move);
this.transform.Rotate(this.rotation);
character.Move(move * speed);
//this.transform.TransformDirection(this.jump);
if (Input.GetKey(KeyCode.Z))
{
character.height = .75f;
//character.speed = 8f;
character.Move(move * crouchSpeed);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(highJump * -2f * gravity);
}
}
else
{
character.height = 1.5f;
//character.speed = 10f;
character.Move(move * speed);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
}
}
character.Move(movement * speed*Time.deltaTime);
//if (Input.GetButtonDown("Jump") && isGrounded)
//{
//velocity.y = Mathf.Sqrt(jump * -2f * gravity);
//}
velocity.y += gravity * Time.deltaTime;
character.Move(velocity * Time.deltaTime);
}
private void FixedUpdate()
{
}
}
What's the fastest way I can code for terminal velocity?