Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- namespace UnitySampleAssets._2D
- {
- public class PlatformerCharacter2D : MonoBehaviour
- {
- private bool facingRight = true;
- [SerializeField] private float maxSpeed = 10f;
- [SerializeField] private float jumpForce = 400f;
- [Range(0, 1)] [SerializeField] private float crouchSpeed = .36f;
- [SerializeField] private bool airControl = false;
- [SerializeField] private LayerMask whatIsGround;
- private Transform groundCheck;
- private float groundedRadius = .2f;
- private bool grounded = false;
- private Transform ceilingCheck;
- private float ceilingRadius = .01f;
- private Animator anim;
- private void Awake()
- {
- groundCheck = transform.Find("GroundCheck");
- ceilingCheck = transform.Find("CeilingCheck");
- anim = GetComponent<Animator>();
- }
- private void FixedUpdate()
- {
- grounded = Physics2D.OverlapCircle(groundCheck.position, groundedRadius, whatIsGround);
- anim.SetBool("Ground", grounded);
- anim.SetFloat("vSpeed", rigidbody2D.velocity.y);
- }
- public void Move(float move, bool crouch, bool jump)
- {
- if (!crouch && anim.GetBool("Crouch"))
- {
- if (Physics2D.OverlapCircle(ceilingCheck.position, ceilingRadius, whatIsGround))
- crouch = true;
- }
- anim.SetBool("Crouch", crouch);
- if (grounded || airControl)
- {
- move = (crouch ? move*crouchSpeed : move);
- anim.SetFloat("Speed", Mathf.Abs(move));
- rigidbody2D.velocity = new Vector2(move*maxSpeed, rigidbody2D.velocity.y);
- if (move > 0 && !facingRight)
- Flip();
- else if (move < 0 && facingRight)
- Flip();
- }
- if (grounded && jump && anim.GetBool("Ground"))
- {
- grounded = false;
- anim.SetBool("Ground", false);
- rigidbody2D.AddForce(new Vector2(0f, jumpForce));
- }
- }
- private void Flip()
- {
- facingRight = !facingRight;
- Vector3 theScale = transform.localScale;
- theScale.x *= -1;
- transform.localScale = theScale;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement