Question by
MalcolmFerguson · Jun 09, 2019 at 10:13 PM ·
2djumpplatformerinconsistent
Unity2D Player Jump Heights Inconsistent,Unity2D Inconsistent Player Jump Heights
I'm working on a 2D platformer in Unity. I've used a Tilemap to build the level, and have added the player in. For the most part, the functionality I've got on the player so far seems to work fine, except for one thing - Sometimes he doesn't jump as high as he should, though other times it seems to work fine. Does anyone know how I can fix this? Here's my Player.cs script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
// Configuration
[SerializeField] float moveSpeed = 5.0f;
[SerializeField] float jumpSpeed = 4.0f;
// State variables
bool isAlive = true;
// Cached component references
Rigidbody2D myRigidbody;
Animator myAnimator;
CapsuleCollider2D myBodyCollider;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myBodyCollider = GetComponent<CapsuleCollider2D>();
}
void Update()
{
Move();
Jump();
FlipSprite();
}
private void Move()
{
float direction = Input.GetAxis("Horizontal");
CheckIfRunning();
Vector2 playerVelocity = new Vector2(direction * moveSpeed, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
bool hasHorizSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
myAnimator.SetBool("Running", hasHorizSpeed);
}
private void Jump()
{
if (!myBodyCollider.IsTouchingLayers(LayerMask.GetMask("Ground"))) { return; }
CheckIfRunning();
if (Input.GetButton("Jump"))
{
Vector2 jumpVelocity = new Vector2(0.0f, jumpSpeed);
myRigidbody.velocity += jumpVelocity;
}
bool isJumping = Mathf.Abs(myRigidbody.velocity.y) > Mathf.Epsilon;
myAnimator.SetBool("Jumping", isJumping);
}
private void FlipSprite()
{
bool hasHorizSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
if(hasHorizSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidbody.velocity.x), 1.0f);
}
}
private void CheckIfRunning()
{
if (Input.GetKey(KeyCode.LeftShift))
{
moveSpeed = 10.0f;
jumpSpeed = 4.5f;
}
else
{
moveSpeed = 5.0f;
jumpSpeed = 4.0f;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
how long a bottom being pressed [solved] 3 Answers
Jumping on enemies help 0 Answers
Checking if the player jumps while not grounded 0 Answers
Ground check doesnt work 0 Answers
Rigidbody2D.velocity Interupts Rigidbody2D.AddForce in 2D Platformer 0 Answers