Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [SerializeField]
- private float speed = 5;
- [SerializeField]
- private float gravity = -20;
- [SerializeField]
- private LayerMask collisionMask;
- private BoxCollider2D boxCollider;
- private Vector2 groundNormal;
- private void Awake()
- {
- boxCollider = GetComponent<BoxCollider2D>();
- }
- private void Update()
- {
- float playerInput = Input.GetAxisRaw("Horizontal");
- velocity.x = playerInput * speed;
- velocity.y += gravity * Time.deltaTime;
- MoveCharacter(velocity * Time.deltaTime);
- }
- private void MoveCharacter(Vector2 velocity)
- {
- //Rotate the character
- Quaternion targetRotation = Quaternion.FromToRotation(Vector2.up, groundNormal);
- transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 0.5f);
- groundNormal = Vector2.zero;
- CollideBelow(ref velocity);
- transform.Translate(velocity);
- }
- private void CollideBelow(ref Vector2 deltaMovement)
- {
- float rayLength = 1;
- Vector2 rayOrigin = transform.position;
- RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -transform.up, rayLength, collisionMask);
- Debug.DrawRay(rayOrigin, -transform.up * rayLength, Color.red);
- if (hit)
- {
- velocity.y = 0;
- deltaMovement.y = -(hit.distance - boxCollider.size.y * 0.5f);
- groundNormal = hit.normal;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement