Vector2 playerPos = transform.position; float capsuleRadius = 0.5f; float capsuleHeight = 2f; // Height of the capsule from bottom center to top center Vector2 capsuleDirection = Vector2.up; // Cast in the upward direction to check for obstacles above the player float maxDistance = 2f; // Maximum distance to cast the ray int layerMask = LayerMask.GetMask("Obstacles"); // Only check for collisions with objects on the "Obstacles" layer RaycastHit2D hit = Physics2D.CapsuleCast(playerPos, new Vector2(capsuleRadius, capsuleHeight), CapsuleDirection, 0f, capsuleDirection, maxDistance, layerMask); if (hit.collider != null) { Debug.Log("Cannot jump over obstacle!"); }
Vector2 projectilePos = transform.position; float capsuleRadius = 0.25f; float capsuleHeight = 0.5f; // Height of the capsule from bottom center to top center Vector2 capsuleDirection = Vector2.right; // Cast in the direction the projectile is traveling float maxDistance = 2f; // Maximum distance to cast the ray int layerMask = LayerMask.GetMask("Targets"); // Only check for collisions with objects on the "Targets" layer RaycastHit2D hit = Physics2D.CapsuleCast(projectilePos, new Vector2(capsuleRadius, capsuleHeight), CapsuleDirection, 0f, capsuleDirection, maxDistance, layerMask); if (hit.collider != null) { // Deal damage to target or trigger other effects }The Physics2D CapsuleCast method is part of the Unity engine's physics library, specifically the `UnityEngine.Physics2D` namespace.