- Home /
Question by
JackalWorks · Nov 08, 2021 at 11:42 AM ·
physicsvelocitycontrolair
How to maintain directional velocity in air but remove control?
I am completely new and implemented a basic character controller with the new input system. Everything works but I am making a platformer and my character has complete control while in air which is too easy, and I want to be able to use my physics materials for when the player lands. If I add an if isGrounded, the player loses all directional velocity. Do i need to use a rigidbody controller?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour{
#pragma warning disable 649
[SerializeField] CharacterController controller;
[SerializeField] float speed = 11f;
Vector2 horizontalInput;
[SerializeField] float jumpHeit = 3.5f;
bool jump;
[SerializeField] float gravity = -30f;
Vector3 verticalVelocity = Vector3.zero;
[SerializeField] LayerMask groundMask;
bool isGrounded;
private void Update()
{
isGrounded = Physics.CheckSphere(transform.position, 0.1f, groundMask);
//fixing jiggle jump
if (isGrounded)
{
controller.stepOffset = 0.5f;
}
else
{
controller.stepOffset = 0f;
}
//turns off velocity in y direction when grounded
if (isGrounded)
{
verticalVelocity.y = 0;
}
//Movement
Vector3 horizontalVelocity = (transform.right * horizontalInput.x + transform.forward * horizontalInput.y) * speed;
controller.Move(horizontalVelocity * Time.deltaTime);
// Jump: v = sqrt(-2 * jumpHeit * gravity)
if (jump)
{
if (isGrounded)
{
verticalVelocity.y = Mathf.Sqrt(-2f * jumpHeit * gravity);
}
jump = false;
}
verticalVelocity.y += gravity * Time.deltaTime;
controller.Move(verticalVelocity * Time.deltaTime);
}
public void RecieveInput (Vector2 _horizontalInput)
{
horizontalInput = _horizontalInput;
}
public void OnJumpPress()
{
jump = true;
}
}
Comment
Your answer
Follow this Question
Related Questions
How to make camera position relative to a specific target. 1 Answer
Obtaining Constant Speed with AddForce 1 Answer
Physics in 2d arkanoid. Tangential and normal velocity 1 Answer
Velocity Movement & Physics Interactions by Rigidbody2D 0 Answers
How to plot velocity of vehicle wheel collider on realtime graph 0 Answers