using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementController : MonoBehaviour
{
public float maxSpeed = 10f;
bool facingRight = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 0f;
bool isCrouching = false;
public float colliderCrouch = 0f;
public float colliderStand = 0f;
bool ceiling;
public Transform ceilingCheck;
float ceilingRadius = 0.2f;
public LayerMask whatIsCeiling;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(grounded && Input.GetButtonDown("Jump"))
{
anim.SetBool("Ground", false);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
}
//On button press player BoxCollider2D is reduced by float colliderCrouch
if (grounded && Input.GetButtonDown("Crouch"))
{
GetComponent<BoxCollider2D>().size = new Vector2(0.2193601f, colliderCrouch);
GetComponent<BoxCollider2D>().offset = new Vector2(0, -.25f);
isCrouching = true;
}
//On button release player BoxCollider2D enlarges by float colliderStand
if (!ceiling && Input.GetButtonUp("Crouch"))
{
GetComponent<BoxCollider2D>().size = new Vector2(0.2193601f, colliderCrouch);
GetComponent<BoxCollider2D>().offset = new Vector2(0, -.25f);
isCrouching = false;
}
//If the GameObject is not crouching, send that the Boolean “Crouch” is false to the Animator. The crouch animation does not play.
if (isCrouching == false)
anim.SetBool("Crouch", false);
//The GameObject is crouching, so send the Boolean as enabled to the Animator. The crouch animation plays.
if (isCrouching == true)
anim.SetBool("Crouch", true);
}
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
anim.SetBool("Ground", grounded);
ceiling = Physics2D.OverlapCircle(ceilingCheck.position, ceilingRadius, whatIsCeiling);
anim.SetBool("Ceil", ceiling);
anim.SetFloat("vSpeed", GetComponent<Rigidbody2D>().velocity.y);
float move = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(move));
GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 &&!facingRight)
Flip();
else if (move < 0 && facingRight)
Flip();
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}