Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //version 1.0 🤣
- using UnityEngine;
- [RequireComponent(typeof(Rigidbody2D))]
- [RequireComponent(typeof(CircleCollider2D))]
- public class Player : MonoBehaviour
- {
- [Header("Player Physics Settings")]
- [SerializeField] Rigidbody2D m_rigidbody2D;
- [SerializeField] float m_speed = 5.0f;
- [SerializeField] float m_jumpForce = 5.0f;
- [Header("Player Grounded Settings")]
- [SerializeField] LayerMask layerMask;
- [SerializeField] float distanceA = 0.7f;
- [SerializeField] float distanceB = 0.9f;
- [SerializeField] float distanceC = 0.9f;
- [Header("Player Debug")]
- [SerializeField] float horizontal;
- [SerializeField] Vector2 direction;
- [SerializeField] Vector2 lastVelocity;
- [SerializeField] bool isGrounded;
- [SerializeField] bool isJump;
- private Transform tx;
- private RaycastHit2D hit;
- private void Reset()
- {
- m_rigidbody2D = GetComponent<Rigidbody2D>();
- }
- private void Start()
- {
- tx = this.transform;
- direction = new Vector2(0, 0);
- }
- private void FixedUpdate()
- {
- isGrounded = IsGrounded();
- if (!isGrounded)
- return;
- Move();
- Jump();
- }
- private void Move()
- {
- horizontal = Input.GetAxis("Horizontal");
- lastVelocity = m_rigidbody2D.velocity;
- direction.x = horizontal;
- direction.y = 0;
- lastVelocity.x = 0;
- m_rigidbody2D.velocity = lastVelocity + direction * m_speed;
- }
- private void ResetJump()
- {
- isJump = false;
- }
- private void Jump()
- {
- if (isJump)
- return;
- if (!Input.GetKey(KeyCode.Space))
- return;
- m_rigidbody2D.AddForce(Vector2.up * m_jumpForce, ForceMode2D.Impulse);
- isJump = true;
- this.Invoke(nameof(ResetJump), 0.5f);
- }
- private void OnDrawGizmos()
- {
- if (!tx)
- return;
- Debug.DrawRay(tx.position, Vector2.down * distanceA, Color.red);
- Debug.DrawRay(tx.position, (Vector2.down + Vector2.left).normalized * distanceB, Color.red);
- Debug.DrawRay(tx.position, (Vector2.down + Vector2.right).normalized * distanceC, Color.red);
- }
- bool IsGrounded()
- {
- hit = Physics2D.Raycast(tx.position, Vector2.down , distanceA, layerMask);
- if (hit.collider != null)
- return true;
- hit =
- Physics2D.Raycast(tx.position, (Vector2.down + Vector2.left), distanceB, layerMask);
- if (hit.collider != null)
- return true;
- hit =
- Physics2D.Raycast(tx.position, Vector2.down + Vector2.right, distanceC, layerMask);
- if (hit.collider != null)
- return true;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement