- Home /
Question by
Wmejeo · Mar 02 at 07:54 PM ·
scripting problemscripting beginner
Jumping makes the player jump 2 times,
I made a small script to make the player jump, so I can jump. I used a spherecast for the groundcheck, but the spherecast either doesn't let me jump at all (if the ray is too short), or makes me jump twice int two following frames. I made a variable that makes you unable to jump for some time after jumping, thinking that it would let me jump again when I was in the air already, but it still jumped twice, although I was clearly not touching the ground.
Code:
float jump;
int jumpCounter = 0;
int noJump = 0;
Rigidbody playerRb;
RaycastHit groundRayInfo;
public int noJumpFrames = 1;
public float sphereRadius = 0.4f;
public int jumpCount = 1;
public float ray = 0.11f;
public float jumpForce = 150;
void Start()
{
playerRb = GetComponent<Rigidbody>();
Time.fixedDeltaTime = 0.016666666666f;
jumpCounter = 0;
}
void FixedUpdate()
{
jump = Input.GetAxis("Jump");
Debug.Log("noJump " + noJump.ToString());
Debug.Log("jumpCounter " + jumpCounter.ToString());
Mathf.Clamp(jumpCounter, 0f, jumpCount);
if (jumpCounter == jumpCount | noJump != 0)
{
jump = 0;
Debug.Log("condition " + (jumpCounter >= jumpCount | noJump != 0).ToString());
}
if (jump == 1)
{
jumpCounter++;
noJump += noJumpFrames;
} else
{
if (noJump > 0)
{
noJump--;
}
}
Debug.Log("jump " + jump.ToString());
playerRb.AddForce(new Vector3(0f, Vector3.up * jump * jumpForce, 0f));
if (Physics.SphereCast(transform.position, sphereRadius, Vector3.down, out groundRayInfo, ray))
{
jumpCounter = 0;
}
Debug.DrawRay(transform.position, Vector3.down * +(ray + sphereRadius), Color.red); // Visual for me to adjust the ray length
}
,
Comment