SchoolFightingSimple/Assets/Scripts/PlayerMovement.cs

51 lines
1.4 KiB
C#

using Unity.Mathematics;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Vector2 spawnedPosition;
public float moveSpeed = 500f;
public float jumpForce = 10f; // The force applied when jumping
public bool isGrounded = false; // To check if the character is on the ground
Rigidbody2D rb;
public float maxSpeed = 5f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
spawnedPosition = transform.position;
}
// Update is called once per frame
void Update()
{
// Check for ground contact using raycast
isGrounded = true;
// Resets the player pos
if (Input.GetKeyDown(KeyCode.Backspace))
{
transform.position = spawnedPosition;
rb.velocity = Vector3.zero;
}
if (Input.GetKey(KeyCode.A))
rb.AddForce(Vector2.left * (Time.deltaTime * moveSpeed));
if (Input.GetKey(KeyCode.D))
rb.AddForce(Vector2.right * (Time.deltaTime * moveSpeed));
// Jumping
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
// Clamps speed
if (math.abs(rb.velocity.x) > maxSpeed)
rb.velocity = new Vector2((rb.velocity.x / math.abs(rb.velocity.x)) * maxSpeed, rb.velocity.y);
}
}