68 lines
1.8 KiB
C#
68 lines
1.8 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public partial class PlayerMain
|
|
{
|
|
[Header("Movement")]
|
|
[SerializeField] private float speed = 8f;
|
|
[SerializeField] private float jumpVelocity = 100f;
|
|
|
|
[Header("Ground")]
|
|
[SerializeField] private LayerMask groundLayer;
|
|
[SerializeField] private float groundDistance = 0.2f;
|
|
[SerializeField] private bool drawDebugRaycasts;
|
|
|
|
private bool _isGrounded;
|
|
private float _footOffset;
|
|
|
|
|
|
private void Input_OnJumpTrigger(object sender, EventArgs e)
|
|
{
|
|
HandleJump();
|
|
}
|
|
|
|
private void MovementHandler()
|
|
{
|
|
Vector2 move = new Vector2(_input.MoveAxis * speed, _rigidbody2D.velocity.y);
|
|
|
|
_rigidbody2D.velocity = move;
|
|
}
|
|
|
|
private void HandleJump()
|
|
{
|
|
if (_isGrounded)
|
|
_rigidbody2D.velocity = Vector2.up * jumpVelocity;
|
|
}
|
|
|
|
void PhysicsCheck()
|
|
{
|
|
_isGrounded = false;
|
|
|
|
RaycastHit2D leftCheck = Raycast(new Vector2(-_footOffset, 0f), Vector2.down, groundDistance);
|
|
RaycastHit2D rightCheck = Raycast(new Vector2(_footOffset, 0f), Vector2.down, groundDistance);
|
|
|
|
if (leftCheck || rightCheck)
|
|
_isGrounded = true;
|
|
}
|
|
|
|
RaycastHit2D Raycast(Vector2 offset, Vector2 rayDirection, float length)
|
|
{
|
|
return Raycast(offset, rayDirection, length, groundLayer);
|
|
}
|
|
|
|
RaycastHit2D Raycast(Vector2 offset, Vector2 rayDirection, float length, LayerMask mask)
|
|
{
|
|
Vector2 pos = transform.position;
|
|
RaycastHit2D hit = Physics2D.Raycast(pos + offset, rayDirection, length, mask);
|
|
|
|
if (drawDebugRaycasts)
|
|
{
|
|
Color color = hit ? Color.red : Color.green;
|
|
Debug.DrawRay(pos + offset, rayDirection * length, color);
|
|
}
|
|
|
|
return hit;
|
|
}
|
|
} |