Hi guys. I am making a test platformer game in unity2D. I am having no problem with my player movement code. I just wanted to clarify a doubt. First have a look at my code :
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D player;
private float hAxis;
public float moveSpeed = 5f;
public float jumpSpeed = 5f;
private void Start()
{
player = GetComponent<Rigidbody2D>();
}
private void Update()
{
hAxis = Input.GetAxisRaw("Horizontal");
if (Input.GetButton("Jump") && (player.velocity.y == 0))
{
player.velocity = new Vector2(moveSpeed * hAxis, jumpSpeed);
} else
{
player.velocity = new Vector2(moveSpeed * hAxis, player.velocity.y);
}
}
}
The code’s working fine. But i have a doubt at this line :
if (Input.GetButton("Jump") && (player.velocity.y == 0))
I wrote this line so that my player can jump continuously if the user holds the jump button continuously as well as it doesn’t fly. But still, when we reach the highest point of our jump, won’t the Y velocity be 0 again? From what I know, yes, the Y velocity should be 0 again. But, If it does, the code shouldn’t work. Still it is working. Please explain to me why doesn’t the Y velocity happen to be 0. I am pretty new to unity. Please help.