So, i have my player script but there’s just one problem now.
My character keeps going when i release key. Any fixes for this?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed;
public float jumpHeight;
Rigidbody2D myRigidbody2D;
private bool isGrounded;
public LayerMask groundLayers;
void Start()
{
myRigidbody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x - 0.5f, transform.position.y - 0.5f),
new Vector2(transform.position.x + 0.5f, transform.position.y - 0.51f), groundLayers);
//movement
if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
{
Jump();
}
if (Input.GetKeyDown(KeyCode.UpArrow) && !isGrounded)
{
Jump();
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
myRigidbody2D.velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
myRigidbody2D.velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
}
void Jump()
{
myRigidbody2D.velocity = new Vector2(0, jumpHeight);
}
}