Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- [RequireComponent(typeof(BoxCollider2D))]
- public class Logica : MonoBehaviour {
- [SerializeField]
- private LayerMask _layerMask;
- private Vector2 _velocity;
- private const float GRAVATY = -9.8f;
- private int _verticalRayAmount = 4;
- private float _verticalRaySpaceing;
- private BoxCollider2D _collider;
- private Bounds _bounds;
- private float _inset = 0.025f;
- private Vector2 _rayCastPostion;
- private void Start()
- {
- _collider = GetComponent<BoxCollider2D>();
- }
- private void Update()
- {
- _velocity.y += GRAVATY * Time.deltaTime;
- MovePlayer(_velocity);
- }
- private void MovePlayer(Vector2 velocity)
- {
- UpdateBounds();
- VecticalCollision(ref velocity);
- transform.Translate(velocity * Time.deltaTime);
- }
- private void VecticalCollision(ref Vector2 velocity)
- {
- float verticalDirection = Mathf.Sign(velocity.y);
- float verticalRayLenght = Mathf.Abs(velocity.y) + _inset;
- for(int i = 0; i < _verticalRayAmount; i++)
- {
- Vector2 vect = _rayCastPostion + Vector2.right * _verticalRaySpaceing * i;
- Debug.DrawRay(vect, Vector2.up * verticalDirection, Color.green);
- RaycastHit2D rayCastHit = Physics2D.Raycast(vect, Vector2.up * verticalDirection, verticalRayLenght, _layerMask);
- if(rayCastHit)
- {
- velocity.y = (rayCastHit.distance - _inset) * verticalDirection;
- }
- }
- }
- private void UpdateBounds()
- {
- _bounds = _collider.bounds;
- _bounds.Expand(_inset * -2f);
- _rayCastPostion = new Vector2(_bounds.min.x, _bounds.min.y);
- _verticalRaySpaceing = _bounds.size.x / (_verticalRayAmount - 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement