Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Player : MonoBehaviour {
- private Rigidbody2D myRigidbody;
- private Animator myAnimator;
- [SerializeField]
- private float movementSpeed;
- private bool facingRight;
- [SerializeField]
- private bool airControl;
- [SerializeField]
- private Transform[] groundPoints;
- [SerializeField]
- private float groundRadius;
- [SerializeField]
- private LayerMask whatIsGround;
- private bool grounded;
- private bool jump;
- [SerializeField]
- private float jumpForce;
- // Use this for initialization
- void Start () {
- facingRight = true;
- myRigidbody = GetComponent<Rigidbody2D> ();
- myAnimator = GetComponent<Animator> ();
- }
- // Update is called once per frame
- void Update()
- {
- HandleInput ();
- }
- private void FixedUpdate ()
- {
- float horizontal = Input.GetAxis("Horizontal");
- grounded = IsGrounded();
- HandleMovement(horizontal);
- Flip(horizontal);
- HandleLayers ();
- ResetValues ();
- }
- private void HandleMovement(float horizontal)
- {
- if (myRigidbody.velocity.y < 0)
- {
- myAnimator.SetBool ("Land", true);
- }
- if (grounded && jump)
- {
- grounded = false;
- myRigidbody.AddForce(new Vector2(0f,700));
- myAnimator.SetTrigger ("Jump");
- }
- if(grounded || airControl)
- {
- myRigidbody.velocity = new Vector2 (horizontal * movementSpeed, myRigidbody.velocity.y);
- myAnimator.SetFloat ("speed", Mathf.Abs(horizontal));
- }
- }
- private void HandleInput()
- {
- if (Input.GetKeyDown(KeyCode.Space))
- {jump = true;
- }
- }
- private void Flip(float horizontal)
- {
- if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight) {
- facingRight = !facingRight;
- Vector3 theScale = transform.localScale;
- theScale.x *= -1;
- transform.localScale = theScale;
- }
- }
- private void ResetValues()
- {
- jump = false;
- }
- private bool IsGrounded()
- {
- //Cheks if we are falling or if the y axis is steady
- if (myRigidbody.velocity.y <= 0)
- {
- //Runs through all the ground points
- foreach (Transform point in groundPoints)
- {
- //Makes an array of all colliders that are overlapping the ground points
- Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
- //Runs through the colliders to check if we are overlapping something that isn't the player
- for (int i = 0; i < colliders.Length; i++)
- {
- if (colliders[i].gameObject != gameObject) //If we are overlapping something else than our self
- {
- myAnimator.ResetTrigger ("jump");
- myAnimator.SetBool ("Land", false);//Stops the land animation
- return true;
- }
- }
- }
- }
- return false; //We are not grounded
- }
- private void HandleLayers()
- {
- if(!grounded)
- {
- myAnimator.SetLayerWeight (1, 1);
- }
- else
- {
- myAnimator.SetLayerWeight (1, 0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement