Advertisement
jezzye13

Logica

May 15th, 2017
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. [RequireComponent(typeof(BoxCollider2D))]
  6. public class Logica : MonoBehaviour {
  7.  
  8.     [SerializeField]
  9.     private LayerMask _layerMask;
  10.  
  11.     private Vector2 _velocity;
  12.     private const float GRAVATY = -9.8f;
  13.  
  14.     private int _verticalRayAmount = 4;
  15.     private float _verticalRaySpaceing;
  16.  
  17.     private BoxCollider2D _collider;
  18.     private Bounds _bounds;
  19.     private float _inset = 0.025f;
  20.     private Vector2 _rayCastPostion;
  21.  
  22.     private void Start()
  23.     {
  24.         _collider = GetComponent<BoxCollider2D>();
  25.     }
  26.  
  27.     private void Update()
  28.     {
  29.         _velocity.y += GRAVATY * Time.deltaTime;
  30.  
  31.         MovePlayer(_velocity);
  32.     }
  33.  
  34.     private void MovePlayer(Vector2 velocity)
  35.     {
  36.         UpdateBounds();
  37.  
  38.         VecticalCollision(ref velocity);
  39.  
  40.         transform.Translate(velocity * Time.deltaTime);
  41.     }
  42.  
  43.     private void VecticalCollision(ref Vector2 velocity)
  44.     {
  45.         float verticalDirection = Mathf.Sign(velocity.y);
  46.         float verticalRayLenght = Mathf.Abs(velocity.y) + _inset;
  47.  
  48.         for(int i = 0; i < _verticalRayAmount; i++)
  49.         {
  50.             Vector2 vect = _rayCastPostion + Vector2.right * _verticalRaySpaceing * i;
  51.             Debug.DrawRay(vect, Vector2.up * verticalDirection, Color.green);
  52.  
  53.             RaycastHit2D rayCastHit = Physics2D.Raycast(vect, Vector2.up * verticalDirection, verticalRayLenght, _layerMask);
  54.             if(rayCastHit)
  55.             {
  56.                 velocity.y = (rayCastHit.distance - _inset) * verticalDirection;
  57.             }
  58.         }
  59.     }
  60.  
  61.     private void UpdateBounds()
  62.     {
  63.         _bounds = _collider.bounds;
  64.         _bounds.Expand(_inset * -2f);
  65.         _rayCastPostion = new Vector2(_bounds.min.x, _bounds.min.y);
  66.  
  67.         _verticalRaySpaceing = _bounds.size.x / (_verticalRayAmount - 1);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement