- Home /
Movement in mid air
So this is my code so far
using UnityEngine;
using System.Collections;
public class MovementNuri : MonoBehaviour
{
private Vector3 moveVector;
private Vector3 lastMove;
private float speed = 5;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
moveVector.x = Input.GetAxis("Horizontal") * speed;
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetKey(KeyCode.Space))
{
verticalVelocity = jumpForce;
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
moveVector = lastMove;
}
moveVector.y = 0;
moveVector.Normalize();
moveVector *= speed;
moveVector.y = verticalVelocity;
controller.Move(moveVector * Time.deltaTime);
lastMove = moveVector;
}
}
So right now I have it set up so that if I'm moving left or right the momentum will carry on to the jump. But how can I make it so that I can make it so I can still have movement in mid air?
Answer by JC_SummitTech · Dec 03, 2016 at 07:46 AM
Basically, remove line 35.
Thank you that worked but I also wanted to still have momentum carried over from running to a jump, so when you let go of the button it doesn't stop in mid air. How would I do that?
You could use the last$$anonymous$$ove value, but at line 35 ins$$anonymous$$d of setting your move to last$$anonymous$$ove, just use part of it, use moveVector + (last$$anonymous$$ove * 0.5f).
By the way, I notice you are multiplying your x speed twice, I don't think the line 22 should be multiplied by speed for your needs.
Also di$$anonymous$$ish your moveVector value while you are in the air, because you probably don't want your momentum to be constant. Something like last$$anonymous$$ove = last$$anonymous$$ove * (1f- Time.deltaTime); Adjust to your needs.
Answer by Konomira · Dec 11, 2016 at 11:23 PM
Move line 22moveVector.x = Input.GetAxis("Horizontal") * speed;
to insideif(controller.isGrounded){ }
Answer by Farmerfromtexas · Apr 25, 2020 at 06:18 PM
@CyberBlitz55 I know this is an old post but this might be the solution you were looking for:
public float airSpeedModifier = 0.05f; //The higher the modifier value the more air control where 0 = no air control, and 1 = full air control.
private void FixedUpdate()
{
if (!controller.isGrounded)
{
moveVector.x = Mathf.Lerp(lastMove.x, moveVector.x, airSpeedModifier);
moveVector.z = Mathf.Lerp(lastMove.z, moveVector.z, airSpeedModifier);
}
}
In the case of the original post just replace line 35 with the two lines inside the if statement above.
Hope it helps (someone)! :)
Unfortunately I have moved on to completely different projects but the help is greatly appreciated :)