I'm tinkering with a unity2D sidescroller, and am trying to make a player controller to jump. However, when I tell my character to jump, it sometimes jumps twice the distance, and I don't know why. Below is my controller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float playerSpeed = 10;
public float jumpForce = 20;
private bool ableToJump = false;
public GameObject groundCheck; // place an empty object slightly below the character where it will collide with any ground
// Update is called once per frame
void Update()
{
if (Input.GetKey("space") && ableToJump)
{
ableToJump = !ableToJump;
GetComponent<Rigidbody2D>().AddForce(new Vector3(0,1,0) * jumpForce);
}
if (Input.GetKey("a"))
{
transform.Translate(-playerSpeed * Time.deltaTime, 0, 0);
}
if (Input.GetKey("d"))
{
transform.Translate(playerSpeed * Time.deltaTime, 0, 0);
}
// The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
ableToJump = Physics2D.Linecast(transform.position, groundCheck.transform.position, 1 << LayerMask.NameToLayer("Wall"));
}
}
Here is the glitch as it appears when I am previewing the game (watch how the third jump seems to be twice as high). There is no consistency to when it occurs, but it has occurred any time between two in a row and 10-12 between times it happens. I have tried long versus short presses of the jump key (space bar), moving versus standing still, and jumping on different locations. I have also tried disabling animations and waiting between presses versus pressing and holding space, versus pressing space rapidly. The only consistent thing is that sometimes I jump about three blocks (200 x 200px each) high, and sometimes I jump about six blocks high. Any tips are appreciated. Thanks!
Debug.Log()
inside the if block to see if it gets called twice. \$\endgroup\$ – Aditya Yadav Feb 14 '17 at 5:39