Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. [SerializeField]
  2. private float speed = 5;
  3. [SerializeField]
  4. private float gravity = -20;
  5. [SerializeField]
  6. private LayerMask collisionMask;
  7.  
  8. private BoxCollider2D boxCollider;
  9. private Vector2 groundNormal;
  10.  
  11. private void Awake()
  12. {
  13. boxCollider = GetComponent<BoxCollider2D>();
  14. }
  15.  
  16. private void Update()
  17. {
  18. float playerInput = Input.GetAxisRaw("Horizontal");
  19.  
  20. velocity.x = playerInput * speed;
  21. velocity.y += gravity * Time.deltaTime;
  22.  
  23. MoveCharacter(velocity * Time.deltaTime);
  24. }
  25.  
  26. private void MoveCharacter(Vector2 velocity)
  27. {
  28. //Rotate the character
  29. Quaternion targetRotation = Quaternion.FromToRotation(Vector2.up, groundNormal);
  30. transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 0.5f);
  31.  
  32. groundNormal = Vector2.zero;
  33.  
  34. CollideBelow(ref velocity);
  35. transform.Translate(velocity);
  36. }
  37.  
  38. private void CollideBelow(ref Vector2 deltaMovement)
  39. {
  40. float rayLength = 1;
  41. Vector2 rayOrigin = transform.position;
  42.  
  43. RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -transform.up, rayLength, collisionMask);
  44. Debug.DrawRay(rayOrigin, -transform.up * rayLength, Color.red);
  45.  
  46. if (hit)
  47. {
  48. velocity.y = 0;
  49. deltaMovement.y = -(hit.distance - boxCollider.size.y * 0.5f);
  50.  
  51. groundNormal = hit.normal;
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement