- Home /
https://answers.unity.com/questions/361017/slowing-player-speed-when-in-air.html
Jumping increases movement speed
I'm making a game with ball physics and an FPS camera. I have this bug where the player's movement is increased when I jump.
Example:
Running along the Z axis on a plane:
Suddenly jumping:
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
public Camera cam;
public float camDir;
public Rigidbody rb;
public float speed;
float moveFwrd;
float moveSide;
public KeyCode jumpKey;
public KeyCode brakeKey;
public float jumpSpeed;
public float brakeForce=5f;
float DistanceToTheGround;
// Start is called before the first frame update
void Start()
{
DistanceToTheGround = GetComponent<Collider>().bounds.extents.y;
}
void Update()
{
// Input
moveFwrd = Input.GetAxis("Horizontal");
moveSide = Input.GetAxis("Vertical");
// Player Jump
if (Input.GetKeyDown(jumpKey) && Physics.Raycast(transform.position, Vector3.down, DistanceToTheGround + 0.1f))
{
rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
}
// Braking
if (Input.GetKey(brakeKey))
{
rb.angularDrag = brakeForce;
}
else
{
rb.angularDrag = 0.01f;
}
}
void FixedUpdate()
{
// Player Movement
Vector3 movement = cam.transform.right * moveFwrd + cam.transform.forward * moveSide;
movement = movement.normalized;
rb.AddForce(movement * speed);
}
}
Answer by megaspeeder · Sep 11, 2020 at 11:43 AM
This is because of the friction between the floor and your player. In the air, there is (I suppose you haven't changed it) no drag. That's why it moves quicker in air than on ground. Also, if you're in the air, you will be accelerating your object because there are no forces to counteract this. I'd suggest you reduce the force added to zero when the velocity of the rigidbody approaches the maximum speed imposed.
For example:
void FixedUpdate()
{
// Player Movement
Vector3 movement = cam.transform.right * moveFwrd + cam.transform.forward * moveSide;
movement = movement.normalized * maximumSpeed - rb.velocity.magnitude*;
rb.AddForce(movement * speed);
}