using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float velocity;
public bool canIJump;
public float jumpForce;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
leftMovement();
}
if (Input.GetKey(KeyCode.RightArrow))
{
rightMovement();
}
if (Input.GetKey(KeyCode.UpArrow) && canIJump==true)
{
jump();
}
}
public void leftMovement()
{
Vector2 speed = new Vector2(-1 * velocity * Time.deltaTime, rb.velocity.y);
rb.velocity = speed;
}
public void rightMovement()
{
Vector2 speed = new Vector2(1 * velocity * Time.deltaTime, rb.velocity.y);
rb.velocity = speed;
}
public void jump()
{
Vector2 jumpForceDirection = new Vector2(rb.velocity.x, jumpForce * Time.deltaTime);
rb.velocity = jumpForceDirection;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
canIJump = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Floor"))
{
canIJump = false;
}
}
}
I don’t know why but my player jumps higher than he is supposed to. Sometimes happens, and I can’t find a pattern that makes he do that.