- Home /
Momentum locking jump
Hello i am trying to get the jumping in my game to carry the momentum from when your on the ground say if you were staying still you couldn't really move in any direction or if your sprinting forward the jump will carry momentum but you couldn't just stop mid air. I can't figure it out and any help would be nice.(also on a side note the jumps don't stop when you hit something above you and i'm struggling with that as well but not as important) the answer is probably really obvious but thx for the help. here is my code:using System.Collections; using System.Collections.Generic; using UnityEngine;
public class thirdpersonmovement : MonoBehaviour {
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float gravity = -9.8f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y<0)
{
velocity.y = -2f;
}
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (direction.magnitude >= 0.1f)
{
if (Input.GetKey(KeyCode.LeftShift))
{
speed = 10f;
}
else
{
speed = 6f;
}
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
Your answer
Follow this Question
Related Questions
Movement Script for Player... 1 Answer
isGrounded is always false, even with gravity, how do you fix that? 1 Answer
Why does this piece of code work with gravity and this one dosent 2 Answers
Raycast distance affected by momentum of character 0 Answers
Make Rigidbody Character retain momentum 0 Answers