Advertisement
Guest User

Unity: dash & slide along wall

a guest
Mar 31st, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. void Dash(Vector3 normalisedDirection)
  2. {
  3.     var position = transform.position;
  4.     // assume the collider is a circle - if it's not it's a little more complicated
  5.     var collider = GetComponent<CircleCollider2D>();
  6.    
  7.     // store only the first hit, we don't need the rest
  8.     var results = new RaycastHit2D[1];
  9.     // cast our rigidbody
  10.     var hitCount = rbody.Cast(normalisedDirection, results, dashDistance);
  11.     // if we didn't hit anything
  12.     if (hitCount == 0)
  13.     {
  14.         // lerp between our current position and the new dash position
  15.         StartCoroutine(DoDash(position,
  16.             position + normalisedDirection * dashDistance, Vector3.zero, 1));
  17.     }
  18.     else // we hit something
  19.     {
  20.         // get the position minus the collider's radius (so we don't clip into the wall)
  21.         var hitPoint = position + results[0].fraction * (dashDistance - collider.radius) * normalisedDirection;
  22.         // get a vector that is perpendicular to the hit normal
  23.         var perpendicular = new Vector2(results[0].normal.y, -results[0].normal.x);
  24.         // cast a ray in that direction, to slide along the wall - but we only want to go a fraction of the way along our dash, not the entire distance
  25.         var hit = Physics2D.Raycast(hitPoint, perpendicular, dashDistance - results[0].fraction * dashDistance);
  26.         // lerp between the 3 positions
  27.         StartCoroutine(DoDash(position, hitPoint, hit.point, results[0].fraction));
  28.  
  29.     }
  30. }
  31.  
  32. IEnumerator DoDash(Vector3 startPos, Vector3 pos1, Vector3 pos2, float fraction)
  33. {
  34.     float t = 0;
  35.     while (t < 1)
  36.     {
  37.         if (t < fraction)
  38.             transform.position = Vector3.Lerp(startPos, pos1, t/fraction);
  39.         else
  40.             transform.position = Vector3.Lerp(pos1, pos2, (t - fraction)/(1-fraction));
  41.        
  42.         t += Time.deltaTime / dashTime;
  43.         yield return null;
  44.     }
  45.  
  46.     transform.position = Mathf.Approximately(fraction, 1) ? pos1 : pos2;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement