Legacy Documentation: Version 4.5.0

Script language:

  • JS
  • C#
  • Boo
Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

SweepTest(direction: Vector3, hitInfo: RaycastHit, distance: float = Mathf.Infinity): bool;
bool SweepTest(Vector3 direction, RaycastHit hitInfo, float distance = Mathf.Infinity);
def SweepTest(direction as Vector3, hitInfo as RaycastHit, distance as float = Mathf.Infinity) as bool

Parameters

directionThe direction into which to sweep the rigidbody.
hitInfoIf true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).
distanceThe length of the sweep.

Returns

bool True when the rigidbody sweep intersects any collider, otherwise false.

Description

Tests if a rigidbody would collide with anything, if it was moved through the scene.

This is similar to doing a Physics.Raycast for all points contained in any of a Rigidbody's colliders and returning the closest of all hits (if any) reported. This is useful for AI code, when you need to know if an object would fit somewhere without colliding with anything.

Note that this function only works when a primitive collider type (sphere, cube or capsule) is attached to the rigidbody object - mesh colliders will not work, although they can be detected in the scene by the sweep.

See Also: Physics.SphereCast, Physics.CapsuleCast, Rigidbody.SweepTestAll.

	var hit : RaycastHit;

function Update () { // Cast rigidbody shape 10 meters forward, to see if it is about to hit anything if (rigidbody.SweepTest (transform.forward, hit, 10)) { Debug.Log(hit.distance + "mts distance to obstacle"); } }

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public RaycastHit hit;
    void Update() {
        if (rigidbody.SweepTest(transform.forward, out hit, 10))
            Debug.Log(hit.distance + "mts distance to obstacle");
        
    }
}
import UnityEngine
import System.Collections

public class ExampleClass(MonoBehaviour):

	public hit as RaycastHit

	def Update() as void:
		if rigidbody.SweepTest(transform.forward, , 10):
			Debug.Log((hit.distance + 'mts distance to obstacle'))