Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Dash(Vector3 normalisedDirection)
- {
- var position = transform.position;
- // assume the collider is a circle - if it's not it's a little more complicated
- var collider = GetComponent<CircleCollider2D>();
- // store only the first hit, we don't need the rest
- var results = new RaycastHit2D[1];
- // cast our rigidbody
- var hitCount = rbody.Cast(normalisedDirection, results, dashDistance);
- // if we didn't hit anything
- if (hitCount == 0)
- {
- // lerp between our current position and the new dash position
- StartCoroutine(DoDash(position,
- position + normalisedDirection * dashDistance, Vector3.zero, 1));
- }
- else // we hit something
- {
- // get the position minus the collider's radius (so we don't clip into the wall)
- var hitPoint = position + results[0].fraction * (dashDistance - collider.radius) * normalisedDirection;
- // get a vector that is perpendicular to the hit normal
- var perpendicular = new Vector2(results[0].normal.y, -results[0].normal.x);
- // 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
- var hit = Physics2D.Raycast(hitPoint, perpendicular, dashDistance - results[0].fraction * dashDistance);
- // lerp between the 3 positions
- StartCoroutine(DoDash(position, hitPoint, hit.point, results[0].fraction));
- }
- }
- IEnumerator DoDash(Vector3 startPos, Vector3 pos1, Vector3 pos2, float fraction)
- {
- float t = 0;
- while (t < 1)
- {
- if (t < fraction)
- transform.position = Vector3.Lerp(startPos, pos1, t/fraction);
- else
- transform.position = Vector3.Lerp(pos1, pos2, (t - fraction)/(1-fraction));
- t += Time.deltaTime / dashTime;
- yield return null;
- }
- transform.position = Mathf.Approximately(fraction, 1) ? pos1 : pos2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement