I can’t understand why this code changes the player’s speed when standing on a platform (so the speed should be 0). As a result, gravity also changes:
This is velocity.y:
The problematic function is this (if I remove it, velocity.y becomes 0 when the player is on a floor):
private void setJumpGravity()
{
if(playerRb.velocity.y < 0)
{
playerRb.gravityScale = fallJumpGravity;
}
else if(playerRb.velocity.y > 0 && Input.GetKey(KeyCode.Space) == false)
{
playerRb.gravityScale = spaceJumpGravity;
}
else
{
playerRb.gravityScale = defaultGravity;
}
}
The whole class is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float horizontalInput;
[SerializeField] private float horizontalSpeed;
private Rigidbody2D playerRb;
private bool isGetSpaceDown;
[SerializeField] private float jumpForce;
[SerializeField] private float fallJumpGravity;
[SerializeField] private float spaceJumpGravity;
private float defaultGravity;
// Start is called before the first frame update
void Awake()
{
playerRb = gameObject.GetComponent<Rigidbody2D>();
defaultGravity = playerRb.gravityScale;
}
void Update()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
if(Input.GetKeyDown(KeyCode.Space))
{
isGetSpaceDown = true;
}
}
// Update is called once per frame
void FixedUpdate()
{
playerRb.velocity = new Vector2(horizontalSpeed * horizontalInput, playerRb.velocity.y);
if(isGetSpaceDown == true)
{
playerRb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
isGetSpaceDown = false;
}
setJumpGravity();
//Debug.Log(playerRb.velocity.y);
Debug.Log(playerRb.gravityScale);
}
private void setJumpGravity()
{
if(playerRb.velocity.y < 0)
{
playerRb.gravityScale = fallJumpGravity;
}
else if(playerRb.velocity.y > 0 && Input.GetKey(KeyCode.Space) == false)
{
playerRb.gravityScale = spaceJumpGravity;
}
else
{
playerRb.gravityScale = defaultGravity;
}
}
}