feat: Player script updates - ground check, flip, animations, and study notes
This commit is contained in:
@@ -2,16 +2,93 @@ using UnityEngine;
|
||||
|
||||
public class Player : MonoBehaviour
|
||||
{
|
||||
public Rigidbody2D rb;
|
||||
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
||||
void Start()
|
||||
private Animator anim;
|
||||
private Rigidbody2D rb;
|
||||
|
||||
[Header("Movement details")]
|
||||
[SerializeField] private float moveSpeed = 4.58f;
|
||||
[SerializeField] private float jumpForce = 12;
|
||||
private bool facingRight = true;
|
||||
private float xInput;
|
||||
|
||||
[Header("Collision details")]
|
||||
[SerializeField] private float groundCheckDistance;
|
||||
[SerializeField] private LayerMask whatIsGround;
|
||||
private bool isGrounded;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
|
||||
rb = GetComponent<Rigidbody2D>();
|
||||
anim = GetComponentInChildren<Animator>();
|
||||
}
|
||||
|
||||
// Update is called once per frame
|
||||
void Update()
|
||||
private void Update()
|
||||
|
||||
{
|
||||
rb.linearVelocity = new Vector2(Input.GetAxis("Horizontal"), rb.linearVelocityY);
|
||||
HandleCollision();
|
||||
HandleInput();
|
||||
HandleMovement();
|
||||
HandleAnimations();
|
||||
HandleFlip();
|
||||
}
|
||||
|
||||
private void HandleInput()
|
||||
{
|
||||
xInput = Input.GetAxisRaw("Horizontal");
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.K))
|
||||
{
|
||||
jump();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void HandleAnimations()
|
||||
{
|
||||
bool isMoving = rb.linearVelocity.x != 0;
|
||||
anim.SetBool("isMoving", isMoving);
|
||||
}
|
||||
|
||||
private void HandleMovement()
|
||||
{
|
||||
rb.linearVelocity = new Vector2(xInput * moveSpeed, rb.linearVelocity.y);
|
||||
}
|
||||
|
||||
private void jump()
|
||||
{
|
||||
if (isGrounded)
|
||||
{
|
||||
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleCollision()
|
||||
{
|
||||
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
|
||||
}
|
||||
|
||||
private void HandleFlip()
|
||||
{
|
||||
if(rb.linearVelocity.x > 0 && facingRight == false)
|
||||
{
|
||||
Flip();
|
||||
}
|
||||
else if (rb.linearVelocity.x < 0 && facingRight == true)
|
||||
{
|
||||
Flip();
|
||||
}
|
||||
}
|
||||
|
||||
private void Flip()
|
||||
{
|
||||
transform.Rotate(0, 180, 0);
|
||||
facingRight = !facingRight;
|
||||
}
|
||||
|
||||
private void OnDrawGizmos()
|
||||
{
|
||||
Gizmos.DrawLine(transform.position, transform.position + new Vector3(0, -groundCheckDistance));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user