I am new to Unity and c#, i am trying to build my first game and i have a problem with my player(which is a cube) jumping. It seems like when i start a scene or the game The first jump is extremly high. but after reloading the scene or jumping some more the jump is like intended.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 1000f;
public float sideForce = 100f;
public float jumpForce = 2700f;
public Transform groundCheck;
public float groundDistance = 0.2f;
public LayerMask groundMask;
public bool IsGrounded;
public bool IsJumping;
public float rotateAmount = 1f;
public float boostSpeed = 500f;
public float respawnBoarder = 8f;
void Update() {
if(IsGrounded && Input.GetKeyDown("space")){
rb.AddForce(0, jumpForce * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void FixedUpdate()
{
IsGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
rb.AddForce(0,0,forwardForce * Time.deltaTime);
if(Input.GetKey("d")){
rb.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(Input.GetKey("a")){
rb.AddForce(-sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if(rb.position.y < -1f){
FindObjectOfType<GameManager>().EndGame();
}
if(rb.position.x < -respawnBoarder){
FindObjectOfType<GameManager>().EndGame();
}
if(rb.position.x > respawnBoarder){
FindObjectOfType<GameManager>().EndGame();
}
if(Input.GetKey("w")){
rb.AddForce(0,0,boostSpeed * Time.deltaTime);
transform.Rotate(Vector3.right * rotateAmount);
}
}
}
CodePudding user response:
My guess would be that the jump is triggering more than once in some cases. If so, setting IsGrounded
to false
immediately after the jump may solve it, but to be honest I wonder whether the IsGrounded
check in FixedUpdate()
should additionally be checking whether the player is moving upwards or similar. It looks to me like IsGrounded
could potentially be immediately reenabled if the player hasn't moved far enough away from the ground before the next FixedUpdate()
rolls around.
CodePudding user response:
You should check inputs in the Update()
but not handle the physic operations in it. IsGrounded sets later and thats causes more than one jump. Also the reason why its getting normal could be that your fps getting lower over time.
After getting the input you could store another bool for that it's pressed and handle it after next FixedUpdate.