Vector3.Reflect Method (Vector3, Vector3, Vector3)
Returns the reflection of a vector off a surface that has the specified normal.
Namespace: Microsoft.Xna.Framework
Assembly: Microsoft.Xna.Framework (in microsoft.xna.framework.dll)
Syntax
public static void Reflect (
ref Vector3 vector,
ref Vector3 normal,
out Vector3 result
)
Parameters
- vector
Source vector. - normal
Normal of the surface. - result
[OutAttribute] The reflected vector.
Remarks
Reflect only gives the direction of a reflection off a surface, it does not determine whether the original vector was close enough to the surface to hit it.
Example
Determining the position of a moving particle taking into account a surface being struck.
static Nullable<float> RayPlaneIntersection( ref Ray ray, ref Plane plane )
{
Vector3 PointOnPlane = plane.D * plane.Normal;
float DotNormalDir = Vector3.Dot( plane.Normal, ray.Direction );
if (DotNormalDir == 0) return null;
float d = Vector3.Dot( plane.Normal, PointOnPlane - ray.Position ) / DotNormalDir;
return d;
}
// Set the position of the particle.
Vector3 position = new Vector3( -19, 0, -3 );
// Set the direction in which the particle is moving.
Vector3 direction = new Vector3( 1, 0, 0 );
// Set the speed at which the particle is moving.
float speed = 4.0f;
//Define a plane with a slope of -1 with respect to the xz-axis and passing through (-5, 0, -5).
Plane surface = new Plane( new Vector3( -1f / (float)Math.Sqrt( 2 ), 0, -1f / (float)Math.Sqrt( 2 ) ), 5f * (float)Math.Sqrt( 2 ) );
void MoveParticle()
{
Ray ray = new Ray( position, direction );
bool intersected = true;
Nullable<float> collisionDistance = RayPlaneIntersection( ref ray, ref surface );
// The direction of movement is parallel to the plane.
if (collisionDistance.HasValue == false)
{
intersected = false;
}
// The intersection is opposite the direction of movement.
else if ((collisionDistance.Value <= 0 && speed > 0) ||
(collisionDistance.Value > 0 && speed <= 0))
{
intersected = false;
}
// The intersection is further away than the distance moved.
else if (Math.Abs( collisionDistance.Value ) > Math.Abs( speed ))
{
intersected = false;
}
if (intersected == true) // The particle hit the surface, so reflect it off the surface.
{
// If the vector position + direction * speed passes through the plane, calculate the reflection.
Vector3 reflectionVector = Vector3.Reflect( direction, surface.Normal );
// Calculate the distance left to move after hitting the surface.
float lengthOfReflection = (speed - collisionDistance.Value);
Vector3 newPosition = position + direction * collisionDistance.Value + lengthOfReflection * reflectionVector;
position = newPosition;
direction = reflectionVector;
}
else // There is no intersection, so just move normally.
{
position += direction * speed;
}
}
See Also
Reference
Vector3 Structure
Vector3 Members
Microsoft.Xna.Framework Namespace
Platforms
Xbox 360, Windows XP SP2, Windows Vista