Hello im still new to unity development and im trying to get the main character to jump and the best i can get is it will jump if and only if i hold down the jump button, and if i don’t instead my y axis changes to wherever i am at when i lift my finger off the jump button, so if i spam the jump button i just climb and leave the level. I have my jump animation through the actual animation clip. Here is the code.
using UnityEngine;
public class CharacterMovement : MonoBehaviour {
// RidgidBody component instance for the player
private Rigidbody2D playerRigidBody2D;
// Variable to track how much movement is needed from input
private float movePlayerVector;
// Referencing to the player's animator component.
private Animator anim;
// For determining which way the player is currently facing.
private bool facingRight;
// For determining if the jump is activated
private bool characterJump;
// Speed modifier for player movement
public float speed = 4.0f;
// Reference to the player's sprite GameObject
private GameObject playerSprite;
// Initialize any component references
void Awake() {
playerRigidBody2D = (Rigidbody2D)GetComponent(typeof(Rigidbody2D));
playerSprite = transform.Find("PlayerSprite").gameObject;
anim = (Animator)playerSprite.GetComponent(typeof(Animator));
}
// Update is called once per frame
void Update() {
// Cache the horizontal input.
movePlayerVector = Input.GetAxis("Horizontal");
characterJump = Input.GetButton("Jump");
anim.SetBool("jump", characterJump);
anim.SetFloat("speed", Mathf.Abs(movePlayerVector));
playerRigidBody2D.velocity = new Vector2(movePlayerVector * speed, playerRigidBody2D.velocity.y);
if (movePlayerVector > 0 && !facingRight) {
Flip();
}
else if (movePlayerVector < 0 && facingRight) {
Flip();
}
}
void Flip() {
// Switch the way the player is labeled as facing.
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = playerSprite.transform.localScale;
theScale.x *= -1;
playerSprite.transform.localScale = theScale;
}
}