Collider.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. namespace BansheeEngine
  5. {
  6. /// <summary>
  7. /// Collider represents physics geometry that can be in multiple states:
  8. /// - Default: Static geometry that physics objects can collide with.
  9. /// - Trigger: Static geometry that can't be collided with but will report touch events.
  10. /// - Dynamic: Dynamic geometry that is a part of a Rigidbody.A set of colliders defines the shape of the parent
  11. /// rigidbody.
  12. /// </summary>
  13. public abstract class Collider : Component
  14. {
  15. internal NativeCollider native;
  16. protected Rigidbody parent;
  17. [SerializeField]
  18. internal SerializableData serializableData = new SerializableData();
  19. /// <summary>
  20. /// Triggered when some object starts interacting with the collider. Only triggered if proper collision report mode
  21. /// is turned on.
  22. /// </summary>
  23. public event Action<CollisionData> OnCollisionBegin;
  24. /// <summary>
  25. /// Triggered for every frame that an object remains interacting with a collider. Only triggered if proper collision
  26. /// report mode is turned on.
  27. /// </summary>
  28. public event Action<CollisionData> OnCollisionStay;
  29. /// <summary>
  30. /// Triggered when some object stops interacting with the collider. Only triggered if proper collision report mode
  31. /// is turned on.
  32. /// </summary>
  33. public event Action<CollisionData> OnCollisionEnd;
  34. /// <summary>
  35. /// Determines how the collider used. A trigger will not be used for collisions (objects will pass through it),
  36. /// but collision events will still be reported.
  37. /// </summary>
  38. public bool IsTrigger
  39. {
  40. get { return serializableData.isTrigger; }
  41. set
  42. {
  43. if (serializableData.isTrigger == value)
  44. return;
  45. serializableData.isTrigger = value;
  46. if (native != null)
  47. {
  48. native.IsTrigger = value;
  49. UpdateParentRigidbody();
  50. UpdateTransform();
  51. }
  52. }
  53. }
  54. /// <summary>
  55. /// Determines mass of the collider. Only relevant if the collider is part of a rigidbody. Ultimately this will
  56. /// determine the total mass, center of mass and inertia tensors of the parent rigidbody(if they're being calculated
  57. /// automatically).
  58. /// </summary>
  59. public float Mass
  60. {
  61. get { return serializableData.mass; }
  62. set
  63. {
  64. if (serializableData.mass == value)
  65. return;
  66. serializableData.mass = value;
  67. if (native != null)
  68. {
  69. native.Mass = value;
  70. if (parent != null)
  71. parent.UpdateMassDistribution();
  72. }
  73. }
  74. }
  75. /// <summary>
  76. /// Physics material that determines how objects hitting the collider behave.
  77. /// </summary>
  78. public PhysicsMaterial Material
  79. {
  80. get { return serializableData.material; }
  81. set
  82. {
  83. serializableData.material = value;
  84. if (native != null)
  85. native.Material = value;
  86. }
  87. }
  88. /// <summary>
  89. /// Determines how far apart do two shapes need to be away from each other before the physics runtime starts
  90. /// generating repelling impulse for them.This distance will be the sum of contact offsets of the two interacting
  91. /// objects.If objects are moving fast you can increase this value to start generating the impulse earlier and
  92. /// potentially prevent the objects from interpenetrating. This value is in meters. Must be positive and larger
  93. /// than <see cref="RestOffset"/>.
  94. /// </summary>
  95. public float ContactOffset
  96. {
  97. get { return serializableData.contactOffset; }
  98. set
  99. {
  100. value = MathEx.Max(0, MathEx.Max(value, RestOffset));
  101. serializableData.contactOffset = value;
  102. if (native != null)
  103. native.ContactOffset = value;
  104. }
  105. }
  106. /// <summary>
  107. /// Determines at what distance should two objects resting on one another come to an equilibrium. The value used in the
  108. /// runtime will be the sum of rest offsets for both interacting objects. This value is in meters. Cannot be larger
  109. /// than <see cref="ContactOffset"/>
  110. /// </summary>
  111. public float RestOffset
  112. {
  113. get { return serializableData.restOffset; }
  114. set
  115. {
  116. value = MathEx.Min(value, ContactOffset);
  117. serializableData.restOffset = value;
  118. if (native != null)
  119. native.RestOffset = value;
  120. }
  121. }
  122. /// <summary>
  123. /// Determines with which objects will the collider collide. Objects that are allowed to collide with this
  124. /// object must have the same bits set in their own layers.
  125. /// </summary>
  126. public ulong Layer
  127. {
  128. get { return serializableData.layer; }
  129. set
  130. {
  131. serializableData.layer = value;
  132. if (native != null)
  133. native.Layer = value;
  134. }
  135. }
  136. /// <summary>
  137. /// Determines which (if any) collision events are reported.
  138. /// </summary>
  139. public CollisionReportMode CollisionReportMode
  140. {
  141. get { return serializableData.collisionReportMode; }
  142. set
  143. {
  144. serializableData.collisionReportMode = value;
  145. if (native != null)
  146. UpdateCollisionReportMode();
  147. }
  148. }
  149. /// <summary>
  150. /// Checks does the ray hit this collider.
  151. /// </summary>
  152. /// <param name="ray">Ray to check.</param>
  153. /// <param name="hit">Information about the hit. Valid only if the method returns true.</param>
  154. /// <param name="maxDist">Maximum distance from the ray origin to search for hits.</param>
  155. /// <returns>True if the ray has hit the collider.</returns>
  156. public bool Raycast(Ray ray, out PhysicsQueryHit hit, float maxDist)
  157. {
  158. return Raycast(ray.origin, ray.direction, out hit, maxDist);
  159. }
  160. /// <summary>
  161. /// Checks does the ray hit this collider.
  162. /// </summary>
  163. /// <param name="origin">Origin of the ray to check.</param>
  164. /// <param name="unitDir">Unit direction of the ray to check.</param>
  165. /// <param name="hit">Information about the hit. Valid only if the method returns true.</param>
  166. /// <param name="maxDist">Maximum distance from the ray origin to search for hits.</param>
  167. /// <returns>True if the ray has hit the collider.</returns>
  168. public bool Raycast(Vector3 origin, Vector3 unitDir, out PhysicsQueryHit hit, float maxDist = float.MaxValue)
  169. {
  170. hit = new PhysicsQueryHit();
  171. if (native == null)
  172. return false;
  173. ScriptPhysicsQueryHit scriptHit;
  174. bool wasHit = native.Raycast(origin, unitDir, out scriptHit, maxDist);
  175. hit.collider = scriptHit.collider.Component;
  176. hit.distance = scriptHit.distance;
  177. hit.normal = scriptHit.normal;
  178. hit.point = scriptHit.point;
  179. hit.triangleIdx = scriptHit.triangleIdx;
  180. hit.uv = scriptHit.uv;
  181. return wasHit;
  182. }
  183. /// <summary>
  184. /// Creates an internal instance of the collider. Should be overriden by specific collider implementations.
  185. /// </summary>
  186. /// <returns>An instance of a specific internal collider implementation. </returns>
  187. internal abstract NativeCollider CreateCollider();
  188. /// <summary>
  189. /// Changes the rigidbody parent of the collider. Meant to be called from the Rigidbody itself.
  190. /// </summary>
  191. /// <param name="rigidbody">New rigidbody to assign as the parent to the collider.</param>
  192. /// <param name="isInternal">If true the rigidbody will just be changed internally, but parent rigidbody will not be
  193. /// notified.</param>
  194. internal void SetRigidbody(Rigidbody rigidbody, bool isInternal = false)
  195. {
  196. if (rigidbody == parent)
  197. return;
  198. if (native != null && !isInternal)
  199. {
  200. if (parent != null)
  201. parent.RemoveCollider(this);
  202. NativeRigidbody nativeRigidbody = null;
  203. if (rigidbody != null)
  204. nativeRigidbody = rigidbody.native;
  205. native.Rigidbody = nativeRigidbody;
  206. if (rigidbody != null)
  207. rigidbody.AddCollider(this);
  208. }
  209. parent = rigidbody;
  210. UpdateCollisionReportMode();
  211. }
  212. /// <summary>
  213. /// Triggered when the internal collider begins touching another object.
  214. /// </summary>
  215. /// <param name="data">Data about the collision.</param>
  216. internal void DoOnCollisionBegin(CollisionData data)
  217. {
  218. if (OnCollisionBegin != null)
  219. OnCollisionBegin(data);
  220. }
  221. /// <summary>
  222. /// Triggered when the internal collider ends touching another object.
  223. /// </summary>
  224. /// <param name="data">Data about the collision.</param>
  225. internal void DoOnCollisionStay(CollisionData data)
  226. {
  227. if (OnCollisionStay != null)
  228. OnCollisionStay(data);
  229. }
  230. /// <summary>
  231. /// Triggered when the internal collider ends touching another object.
  232. /// </summary>
  233. /// <param name="data">Data about the collision.</param>
  234. internal void DoOnCollisionEnd(CollisionData data)
  235. {
  236. if (OnCollisionEnd != null)
  237. OnCollisionEnd(data);
  238. }
  239. /// <summary>
  240. /// Checks is the provided rigidbody a valid parent for this collider.
  241. ///
  242. /// This is required because certain colliders are limited in how they can be used.
  243. /// </summary>
  244. /// <param name="parent">Rigidbody that is the potential parent.</param>
  245. /// <returns>True if collider can be a part of the rigidbody.</returns>
  246. protected internal virtual bool IsValidParent(Rigidbody parent)
  247. {
  248. return true;
  249. }
  250. /// <summary>
  251. /// Searches the parent scene object hierarchy to find a parent Rigidbody component.
  252. /// </summary>
  253. protected void UpdateParentRigidbody()
  254. {
  255. if (serializableData.isTrigger)
  256. {
  257. SetRigidbody(null);
  258. return;
  259. }
  260. SceneObject currentSO = SceneObject;
  261. while (currentSO != null)
  262. {
  263. Rigidbody parent = currentSO.GetComponent<Rigidbody>();
  264. if (parent != null)
  265. {
  266. if (currentSO.Active && IsValidParent(parent))
  267. SetRigidbody(parent);
  268. else
  269. SetRigidbody(null);
  270. return;
  271. }
  272. currentSO = currentSO.Parent;
  273. }
  274. // Not found
  275. SetRigidbody(null);
  276. }
  277. /// <summary>
  278. /// Updates the transform of the internal Collider representation from the transform of the component's scene object.
  279. /// </summary>
  280. protected void UpdateTransform()
  281. {
  282. Vector3 myScale = SceneObject.Scale;
  283. if (parent != null)
  284. {
  285. Vector3 parentPos = parent.SceneObject.Position;
  286. Quaternion parentRot = parent.SceneObject.Rotation;
  287. Vector3 myPos = SceneObject.Position;
  288. Quaternion myRot = SceneObject.Rotation;
  289. Vector3 scale = parent.SceneObject.Scale;
  290. Vector3 invScale = scale;
  291. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  292. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  293. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  294. Quaternion invRotation = parentRot.Inverse;
  295. Vector3 relativePos = invRotation.Rotate(myPos - parentPos) * invScale;
  296. Quaternion relativeRot = invRotation * myRot;
  297. relativePos = relativePos + myRot.Rotate(serializableData.localPosition * scale);
  298. relativeRot = relativeRot * serializableData.localRotation;
  299. native.Position = relativePos;
  300. native.Rotation = relativeRot;
  301. parent.UpdateMassDistribution();
  302. }
  303. else
  304. {
  305. Quaternion myRot = SceneObject.Rotation;
  306. Vector3 myPos = SceneObject.Position + myRot.Rotate(serializableData.localPosition * myScale);
  307. myRot = myRot * serializableData.localRotation;
  308. native.Position = myPos;
  309. native.Rotation = myRot;
  310. }
  311. native.Scale = myScale;
  312. }
  313. /// <summary>
  314. /// Applies the collision report mode to the internal collider depending on the current state.
  315. /// </summary>
  316. internal void UpdateCollisionReportMode()
  317. {
  318. CollisionReportMode mode = serializableData.collisionReportMode;
  319. if (parent != null)
  320. mode = parent.CollisionReportMode;
  321. if(native != null)
  322. native.CollisionReportMode = mode;
  323. }
  324. private void OnInitialize()
  325. {
  326. NotifyFlags = TransformChangedFlags.Transform | TransformChangedFlags.Parent;
  327. }
  328. private void OnEnable()
  329. {
  330. RestoreNative();
  331. }
  332. private void OnDisable()
  333. {
  334. DestroyNative();
  335. }
  336. private void OnDestroy()
  337. {
  338. DestroyNative();
  339. }
  340. private void OnTransformChanged(TransformChangedFlags flags)
  341. {
  342. if (!SceneObject.Active)
  343. return;
  344. if ((flags & TransformChangedFlags.Parent) != 0)
  345. UpdateParentRigidbody();
  346. // Don't update the transform if it's due to Physics update since then we can guarantee it will remain at the same
  347. // relative transform to its parent
  348. if (Physics.IsUpdateInProgress)
  349. return;
  350. if ((flags & (TransformChangedFlags.Parent | TransformChangedFlags.Transform)) != 0)
  351. UpdateTransform();
  352. }
  353. /// <summary>
  354. /// Destroys the internal collider representation.
  355. /// </summary>
  356. private void DestroyNative()
  357. {
  358. if (parent != null)
  359. parent.RemoveCollider(this);
  360. parent = null;
  361. if (native != null)
  362. {
  363. native.Destroy();
  364. native = null;
  365. }
  366. }
  367. /// <summary>
  368. /// Creates the internal representation of the Collider and restores the values saved by the Component.
  369. /// </summary>
  370. private void RestoreNative()
  371. {
  372. native = CreateCollider();
  373. native.Component = this;
  374. native.Position = serializableData.localPosition;
  375. native.Rotation = serializableData.localRotation;
  376. native.IsTrigger = serializableData.isTrigger;
  377. native.Mass = serializableData.mass;
  378. native.Material = serializableData.material;
  379. native.ContactOffset = serializableData.contactOffset;
  380. native.RestOffset = serializableData.restOffset;
  381. native.Layer = serializableData.layer;
  382. UpdateParentRigidbody();
  383. UpdateTransform();
  384. UpdateCollisionReportMode();
  385. }
  386. /// <summary>
  387. /// Holds all data the collider component needs to persist through serialization.
  388. /// </summary>
  389. [SerializeObject]
  390. internal class SerializableData
  391. {
  392. public Vector3 localPosition = Vector3.Zero;
  393. public Quaternion localRotation = Quaternion.Identity;
  394. public bool isTrigger = false;
  395. public float mass = 1.0f;
  396. public PhysicsMaterial material;
  397. public float contactOffset = 0.02f;
  398. public float restOffset = 0.0f;
  399. public ulong layer = 1;
  400. public CollisionReportMode collisionReportMode = CollisionReportMode.None;
  401. }
  402. }
  403. }