Go to the documentation of this file.00001 using System;
00002 using Microsoft.Xna.Framework;
00003
00004 namespace XnaCollisionLib
00005 {
00006 public struct Triangle
00007 {
00008 public Vector3 A;
00009 public Vector3 B;
00010 public Vector3 C;
00011 public Plane Plane;
00012
00013 public Triangle(Vector3 a, Vector3 b, Vector3 c)
00014 {
00015 A = a;
00016 B = b;
00017 C = c;
00018 Plane = new Plane(A, B, C);
00019 }
00020
00021 public Triangle(Triangle triangle, Matrix transform)
00022 {
00023 A = Vector3.Transform(triangle.A, transform);
00024 B = Vector3.Transform(triangle.B, transform);
00025 C = Vector3.Transform(triangle.C, transform);
00026 Plane = new Plane(A, B, C);
00027 }
00028
00029 public Nullable<float> ISect(Ray ray)
00030 {
00031 Nullable<float> t = ray.Intersects(Plane);
00032
00033 if (t.HasValue && t.Value >= 0)
00034 {
00035 Vector3 point = ray.Position + t.Value * ray.Direction;
00036
00037 if (!IsPointInside(point))
00038 t = null;
00039 }
00040 else
00041 t = null;
00042 return t;
00043 }
00044
00045 public bool IsFronFacing(Vector3 lookDirection)
00046 {
00047 return Vector3.Dot(Plane.Normal, lookDirection) >= 0;
00048 }
00049
00050 public bool IsPointInside(Vector3 point)
00051 {
00052 return
00053 IsOnSameSide(point, A, B, C) &&
00054 IsOnSameSide(point, B, A, C) &&
00055 IsOnSameSide(point, C, A, B);
00056 }
00057
00058 private bool IsOnSameSide(Vector3 p1, Vector3 p2, Vector3 a, Vector3 b)
00059 {
00060 Vector3 a2b = b - a;
00061 Vector3 cp1 = Vector3.Cross(a2b, p1 - a);
00062 Vector3 cp2 = Vector3.Cross(a2b, p2 - a);
00063
00064 return Vector3.Dot(cp1, cp2) >= 0;
00065 }
00066 }
00067 }