2023-08-20 03:31:31 +02:00
|
|
|
using Unity.Mathematics;
|
2023-08-18 03:06:44 +02:00
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
public class PlayerMovement : MonoBehaviour
|
|
|
|
{
|
2023-08-20 03:31:31 +02:00
|
|
|
Vector2 spawnedPosition;
|
2023-08-18 03:06:44 +02:00
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
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;
|
2023-08-18 03:06:44 +02:00
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
public float maxSpeed = 5f;
|
|
|
|
|
|
|
|
// Start is called before the first frame update
|
|
|
|
void Start()
|
2023-08-18 03:06:44 +02:00
|
|
|
{
|
|
|
|
rb = GetComponent<Rigidbody2D>();
|
2023-08-20 03:31:31 +02:00
|
|
|
spawnedPosition = transform.position;
|
2023-08-18 03:06:44 +02:00
|
|
|
}
|
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
// Update is called once per frame
|
|
|
|
void Update()
|
2023-08-18 03:06:44 +02:00
|
|
|
{
|
2023-08-20 03:31:31 +02:00
|
|
|
// Check for ground contact using raycast
|
|
|
|
isGrounded = true;
|
2023-08-18 03:06:44 +02:00
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
// Resets the player pos
|
|
|
|
if (Input.GetKeyDown(KeyCode.Backspace))
|
2023-08-18 03:06:44 +02:00
|
|
|
{
|
2023-08-20 03:31:31 +02:00
|
|
|
transform.position = spawnedPosition;
|
|
|
|
rb.velocity = Vector3.zero;
|
2023-08-18 03:06:44 +02:00
|
|
|
}
|
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
if (Input.GetKey(KeyCode.A))
|
|
|
|
rb.AddForce(Vector2.left * (Time.deltaTime * moveSpeed));
|
|
|
|
if (Input.GetKey(KeyCode.D))
|
|
|
|
rb.AddForce(Vector2.right * (Time.deltaTime * moveSpeed));
|
2023-08-18 03:06:44 +02:00
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
// Jumping
|
|
|
|
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
|
2023-08-18 03:06:44 +02:00
|
|
|
{
|
2023-08-20 03:31:31 +02:00
|
|
|
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
|
2023-08-18 03:06:44 +02:00
|
|
|
}
|
|
|
|
|
2023-08-20 03:31:31 +02:00
|
|
|
// 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);
|
2023-08-18 03:06:44 +02:00
|
|
|
}
|
|
|
|
}
|