Advertisement
Guest User

Untitled

a guest
Aug 26th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. namespace UnitySampleAssets._2D
  4. {
  5.  
  6. public class PlatformerCharacter2D : MonoBehaviour
  7. {
  8. private bool facingRight = true;
  9.  
  10. [SerializeField] private float maxSpeed = 10f;
  11. [SerializeField] private float jumpForce = 400f;
  12.  
  13. [Range(0, 1)] [SerializeField] private float crouchSpeed = .36f;
  14.  
  15.  
  16. [SerializeField] private bool airControl = false;
  17. [SerializeField] private LayerMask whatIsGround;
  18.  
  19. private Transform groundCheck;
  20. private float groundedRadius = .2f;
  21. private bool grounded = false;
  22. private Transform ceilingCheck;
  23. private float ceilingRadius = .01f;
  24. private Animator anim;
  25.  
  26.  
  27. private void Awake()
  28. {
  29.  
  30. groundCheck = transform.Find("GroundCheck");
  31. ceilingCheck = transform.Find("CeilingCheck");
  32. anim = GetComponent<Animator>();
  33. }
  34.  
  35.  
  36. private void FixedUpdate()
  37. {
  38.  
  39. grounded = Physics2D.OverlapCircle(groundCheck.position, groundedRadius, whatIsGround);
  40. anim.SetBool("Ground", grounded);
  41.  
  42.  
  43. anim.SetFloat("vSpeed", rigidbody2D.velocity.y);
  44. }
  45.  
  46.  
  47. public void Move(float move, bool crouch, bool jump)
  48. {
  49.  
  50.  
  51.  
  52. if (!crouch && anim.GetBool("Crouch"))
  53. {
  54.  
  55. if (Physics2D.OverlapCircle(ceilingCheck.position, ceilingRadius, whatIsGround))
  56. crouch = true;
  57. }
  58.  
  59.  
  60. anim.SetBool("Crouch", crouch);
  61.  
  62.  
  63. if (grounded || airControl)
  64. {
  65.  
  66. move = (crouch ? move*crouchSpeed : move);
  67.  
  68.  
  69. anim.SetFloat("Speed", Mathf.Abs(move));
  70.  
  71.  
  72. rigidbody2D.velocity = new Vector2(move*maxSpeed, rigidbody2D.velocity.y);
  73.  
  74.  
  75. if (move > 0 && !facingRight)
  76.  
  77. Flip();
  78.  
  79. else if (move < 0 && facingRight)
  80.  
  81. Flip();
  82. }
  83.  
  84. if (grounded && jump && anim.GetBool("Ground"))
  85. {
  86.  
  87. grounded = false;
  88. anim.SetBool("Ground", false);
  89. rigidbody2D.AddForce(new Vector2(0f, jumpForce));
  90. }
  91. }
  92.  
  93.  
  94. private void Flip()
  95. {
  96.  
  97. facingRight = !facingRight;
  98.  
  99.  
  100. Vector3 theScale = transform.localScale;
  101. theScale.x *= -1;
  102. transform.localScale = theScale;
  103. }
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement