public void Move(Vector3 velocity, OnHitCallBack onHitCall) { UpdateRaycastOrigins(); CalculateRaySpacing(); collisions.Reset(); if (velocity.x != 0) { HorizontalCollision(ref velocity, onHitCall); } if (velocity.y != 0) { VerticalCollision(ref velocity, onHitCall); } transform.Translate(velocity); }
private void HorizontalCollision(ref Vector3 velocity, OnHitCallBack onHitCall) { float directionX = Mathf.Sign(velocity.x); float rayLength = Mathf.Abs(velocity.x) + skinWidth; for (int i = 0; i < horizontalRayCount; i++) { Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight; rayOrigin += Vector2.up * horizontalRaySpacing * i; RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask); Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red); if (hit) { velocity.x = (hit.distance - skinWidth) * directionX; rayLength = hit.distance; collisions.left = (directionX == -1); collisions.right = (directionX == 1); onHitCall(hit); } } }
private void VerticalCollision(ref Vector3 velocity, OnHitCallBack onHitCall) { float directionY = Mathf.Sign(velocity.y); float rayLength = Mathf.Abs(velocity.y) + skinWidth; for (int i = 0; i < verticalRayCount; i++) { Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft; Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red); rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask); if (hit) { velocity.y = (hit.distance - skinWidth) * directionY; rayLength = hit.distance; collisions.below = (directionY == -1); collisions.above = (directionY == 1); onHitCall(hit); } } }