- Home /
Character in game not jumping even though script works on other games with different characters
Hi, I am currently struggling to find a solution with my character not being able to jump in my game. The code which I have used has been used in other games which I have created and work fine on all of them.
The objects which I have on my character are a sprite renderer, box collider 2D, Rigidbody 2D, and of course the script in order for the character to move. I have also tried adding on an animator to see if that would work but it either doesn't affect the character at all or it completely leaves it motionless. I have also tried deleting the character and re doing everything to see if it was just a simple mistake that I had done.
Below is the code which I used:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Player : MonoBehaviour {
private Rigidbody2D myRigidBody;
private float canJumpVect;
private bool canJump;
[SerializeField]
private float movementSpeed;
private bool facingRight;
public float thrust;
public static bool Grounded;
void Start () {
facingRight = true;
myRigidBody = GetComponent<Rigidbody2D>();
}
void Update () {
canJumpVect = myRigidBody.transform.position.x;
if (canJumpVect < -5.134499f) {
canJump = false;
} else {
canJump = true;
}
float horizontal = Input.GetAxis ("Horizontal");
//Debug.Log(horizontal);
// float vertical = Input.GetAxis("Vertical");
handleMovement (horizontal);
Flip(horizontal);
if (Input.GetKeyDown(KeyCode.Space) && Grounded == true) {
Debug.Log("jumped");
if (canJump == true) {
myRigidBody.AddForce (transform.up * thrust);
Grounded = false;
}
}
}
private void handleMovement(float horizontal) {
myRigidBody.velocity = new Vector2 (horizontal * movementSpeed, myRigidBody.velocity.y);
}
private void Flip (float horizontal) {
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight) {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
Thank you in advance and I hope that someone will be able to help!
Your answer
