Legacy Documentation: Version 2017.1 (Go to current version)
LanguageEnglish
  • C#
  • JS

Script language

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

Rigidbody.SweepTest

Switch to Manual
public function SweepTest(direction: Vector3, out hitInfo: RaycastHit, maxDistance: float = Mathf.Infinity, queryTriggerInteraction: QueryTriggerInteraction = QueryTriggerInteraction.UseGlobal): bool;

Parameters

direction The direction into which to sweep the rigidbody.
hitInfo If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).
maxDistance The length of the sweep.
queryTriggerInteraction Specifies whether this query should hit Triggers.

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.

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, say if you need to know that an object would fit through a gap without colliding with anything.

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

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

#pragma strict
public var collisionCheckDistance: float;
public var aboutToCollide: boolean;
public var distanceToCollision: float;
public var rb: Rigidbody;
function Start() {
	rb = GetComponent.<Rigidbody>();
}
function Update() {
	var hit: RaycastHit;
	if (rb.SweepTest(transform.forward, hit, collisionCheckDistance)) {
		aboutToCollide = true;
		distanceToCollision = hit.distance;
	}
}

Did you find this page useful? Please give it a rating: