Collider.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 (i.e. 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.
  93. /// </summary>
  94. public float ContactOffset
  95. {
  96. get { return serializableData.contactOffset; }
  97. set
  98. {
  99. serializableData.contactOffset = value;
  100. if (native != null)
  101. native.ContactOffset = value;
  102. }
  103. }
  104. /// <summary>
  105. /// Determines at what distance should two objects resting on one another come to an equilibrium. The value used in the
  106. /// runtime will be the sum of rest offsets for both interacting objects. This value is in meters.
  107. /// </summary>
  108. public float RestOffset
  109. {
  110. get { return serializableData.restOffset; }
  111. set
  112. {
  113. serializableData.restOffset = value;
  114. if (native != null)
  115. native.RestOffset = value;
  116. }
  117. }
  118. /// <summary>
  119. /// Determines with which objects will the collider collide. Objects that are allowed to collide with this
  120. /// object must have the same bits set in their own layers.
  121. /// </summary>
  122. public ulong Layer
  123. {
  124. get { return serializableData.layer; }
  125. set
  126. {
  127. serializableData.layer = value;
  128. if (native != null)
  129. native.Layer = value;
  130. }
  131. }
  132. /// <summary>
  133. /// Determines which (if any) collision events are reported.
  134. /// </summary>
  135. public CollisionReportMode CollisionReportMode
  136. {
  137. get { return serializableData.collisionReportMode; }
  138. set
  139. {
  140. serializableData.collisionReportMode = value;
  141. if (native != null)
  142. UpdateCollisionReportMode();
  143. }
  144. }
  145. /// <summary>
  146. /// Checks does the ray hit this collider.
  147. /// </summary>
  148. /// <param name="ray">Ray to check.</param>
  149. /// <param name="hit">Information about the hit. Valid only if the method returns true.</param>
  150. /// <param name="maxDist">Maximum distance from the ray origin to search for hits.</param>
  151. /// <returns>True if the ray has hit the collider.</returns>
  152. public bool Raycast(Ray ray, out PhysicsQueryHit hit, float maxDist)
  153. {
  154. return Raycast(ray.origin, ray.direction, out hit, maxDist);
  155. }
  156. /// <summary>
  157. /// Checks does the ray hit this collider.
  158. /// </summary>
  159. /// <param name="origin">Origin of the ray to check.</param>
  160. /// <param name="unitDir">Unit direction of the ray to check.</param>
  161. /// <param name="hit">Information about the hit. Valid only if the method returns true.</param>
  162. /// <param name="maxDist">Maximum distance from the ray origin to search for hits.</param>
  163. /// <returns>True if the ray has hit the collider.</returns>
  164. public bool Raycast(Vector3 origin, Vector3 unitDir, out PhysicsQueryHit hit, float maxDist = float.MaxValue)
  165. {
  166. hit = new PhysicsQueryHit();
  167. if (native == null)
  168. return false;
  169. ScriptPhysicsQueryHit scriptHit;
  170. bool wasHit = native.Raycast(origin, unitDir, out scriptHit, maxDist);
  171. hit.collider = scriptHit.collider.Component;
  172. hit.distance = scriptHit.distance;
  173. hit.normal = scriptHit.normal;
  174. hit.point = scriptHit.point;
  175. hit.triangleIdx = scriptHit.triangleIdx;
  176. hit.uv = scriptHit.uv;
  177. return wasHit;
  178. }
  179. /// <summary>
  180. /// Creates an internal instance of the collider. Should be overriden by specific collider implementations.
  181. /// </summary>
  182. /// <returns>An instance of a specific internal collider implementation. </returns>
  183. internal abstract NativeCollider CreateCollider();
  184. /// <summary>
  185. /// Changes the rigidbody parent of the collider. Meant to be called from the Rigidbody itself.
  186. /// </summary>
  187. /// <param name="rigidbody">New rigidbody to assign as the parent to the collider.</param>
  188. /// <param name="isInternal">If true the rigidbody will just be changed internally, but parent rigidbody will not be
  189. /// notified.</param>
  190. internal void SetRigidbody(Rigidbody rigidbody, bool isInternal = false)
  191. {
  192. if (rigidbody == parent)
  193. return;
  194. if (native != null && !isInternal)
  195. {
  196. if (parent != null)
  197. parent.RemoveCollider(this);
  198. NativeRigidbody nativeRigidbody = null;
  199. if (rigidbody != null)
  200. nativeRigidbody = rigidbody.native;
  201. native.Rigidbody = nativeRigidbody;;
  202. if (rigidbody != null)
  203. rigidbody.AddCollider(this);
  204. }
  205. parent = rigidbody;
  206. UpdateCollisionReportMode();
  207. }
  208. /// <summary>
  209. /// Triggered when the internal collider begins touching another object.
  210. /// </summary>
  211. /// <param name="data">Data about the collision.</param>
  212. internal void DoOnCollisionBegin(CollisionData data)
  213. {
  214. if (OnCollisionBegin != null)
  215. OnCollisionBegin(data);
  216. }
  217. /// <summary>
  218. /// Triggered when the internal collider ends touching another object.
  219. /// </summary>
  220. /// <param name="data">Data about the collision.</param>
  221. internal void DoOnCollisionStay(CollisionData data)
  222. {
  223. if (OnCollisionStay != null)
  224. OnCollisionStay(data);
  225. }
  226. /// <summary>
  227. /// Triggered when the internal collider ends touching another object.
  228. /// </summary>
  229. /// <param name="data">Data about the collision.</param>
  230. internal void DoOnCollisionEnd(CollisionData data)
  231. {
  232. if (OnCollisionEnd != null)
  233. OnCollisionEnd(data);
  234. }
  235. /// <summary>
  236. /// Checks is the provided rigidbody a valid parent for this collider.
  237. ///
  238. /// This is required because certain colliders are limited in how they can be used.
  239. /// </summary>
  240. /// <param name="parent">Rigidbody that is the potential parent.</param>
  241. /// <returns>True if collider can be a part of the rigidbody.</returns>
  242. protected internal virtual bool IsValidParent(Rigidbody parent)
  243. {
  244. return true;
  245. }
  246. /// <summary>
  247. /// Searches the parent scene object hierarchy to find a parent Rigidbody component.
  248. /// </summary>
  249. protected void UpdateParentRigidbody()
  250. {
  251. if (serializableData.isTrigger)
  252. {
  253. SetRigidbody(null);
  254. return;
  255. }
  256. SceneObject currentSO = SceneObject;
  257. while (currentSO != null)
  258. {
  259. Rigidbody parent = currentSO.GetComponent<Rigidbody>();
  260. if (parent != null)
  261. {
  262. if (currentSO.Active && IsValidParent(parent))
  263. SetRigidbody(parent);
  264. else
  265. SetRigidbody(null);
  266. return;
  267. }
  268. currentSO = currentSO.Parent;
  269. }
  270. // Not found
  271. SetRigidbody(null);
  272. }
  273. /// <summary>
  274. /// Updates the transform of the internal Collider representation from the transform of the component's scene object.
  275. /// </summary>
  276. protected void UpdateTransform()
  277. {
  278. if (parent != null)
  279. {
  280. Vector3 parentPos = parent.SceneObject.Position;
  281. Quaternion parentRot = parent.SceneObject.Rotation;
  282. Vector3 myPos = SceneObject.Position;
  283. Quaternion myRot = SceneObject.Rotation;
  284. Vector3 scale = parent.SceneObject.Scale;
  285. Vector3 invScale = scale;
  286. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  287. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  288. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  289. Quaternion invRotation = parentRot.Inverse;
  290. Vector3 relativePos = invRotation.Rotate(myPos - parentPos) * invScale;
  291. Quaternion relativeRot = invRotation * myRot;
  292. relativePos = relativePos + myRot.Rotate(serializableData.localPosition * scale);
  293. relativeRot = relativeRot * serializableData.localRotation;
  294. native.Position = relativePos;
  295. native.Rotation = relativeRot;
  296. parent.UpdateMassDistribution();
  297. }
  298. else
  299. {
  300. Vector3 myScale = SceneObject.Scale;
  301. Quaternion myRot = SceneObject.Rotation;
  302. Vector3 myPos = SceneObject.Position + myRot.Rotate(serializableData.localPosition * myScale);
  303. myRot = myRot * serializableData.localRotation;
  304. native.Position = myPos;
  305. native.Rotation = myRot;
  306. }
  307. }
  308. /// <summary>
  309. /// Applies the collision report mode to the internal collider depending on the current state.
  310. /// </summary>
  311. internal void UpdateCollisionReportMode()
  312. {
  313. CollisionReportMode mode = serializableData.collisionReportMode;
  314. if (parent != null)
  315. mode = parent.CollisionReportMode;
  316. native.CollisionReportMode = mode;
  317. }
  318. private void OnInitialize()
  319. {
  320. NotifyFlags = TransformChangedFlags.Transform | TransformChangedFlags.Parent;
  321. }
  322. private void OnReset()
  323. {
  324. RestoreNative();
  325. }
  326. private void OnEnable()
  327. {
  328. if (native == null)
  329. RestoreNative();
  330. }
  331. private void OnDisable()
  332. {
  333. DestroyNative();
  334. }
  335. private void OnDestroy()
  336. {
  337. DestroyNative();
  338. }
  339. private void OnTransformChanged(TransformChangedFlags flags)
  340. {
  341. if (!SceneObject.Active)
  342. return;
  343. if ((flags & TransformChangedFlags.Parent) != 0)
  344. UpdateParentRigidbody();
  345. // Don't update the transform if it's due to Physics update since then we can guarantee it will remain at the same
  346. // relative transform to its parent
  347. if (Physics.IsUpdateInProgress)
  348. return;
  349. if ((flags & (TransformChangedFlags.Parent | TransformChangedFlags.Transform)) != 0)
  350. UpdateTransform();
  351. }
  352. /// <summary>
  353. /// Destroys the internal collider representation.
  354. /// </summary>
  355. private void DestroyNative()
  356. {
  357. if (parent != null)
  358. parent.RemoveCollider(this);
  359. parent = null;
  360. if (native != null)
  361. {
  362. native.Destroy();
  363. native = null;
  364. }
  365. }
  366. /// <summary>
  367. /// Creates the internal representation of the Collider and restores the values saved by the Component.
  368. /// </summary>
  369. private void RestoreNative()
  370. {
  371. native = CreateCollider();
  372. native.Component = this;
  373. native.Position = serializableData.localPosition;
  374. native.Rotation = serializableData.localRotation;
  375. native.IsTrigger = serializableData.isTrigger;
  376. native.Mass = serializableData.mass;
  377. native.Material = serializableData.material;
  378. native.ContactOffset = serializableData.contactOffset;
  379. native.RestOffset = serializableData.restOffset;
  380. native.Layer = serializableData.layer;
  381. UpdateParentRigidbody();
  382. UpdateTransform();
  383. UpdateCollisionReportMode();
  384. }
  385. /// <summary>
  386. /// Holds all data the collider component needs to persist through serialization.
  387. /// </summary>
  388. [SerializeObject]
  389. internal class SerializableData
  390. {
  391. public Vector3 localPosition;
  392. public Quaternion localRotation;
  393. public bool isTrigger;
  394. public float mass = 1.0f;
  395. public PhysicsMaterial material;
  396. public float contactOffset;
  397. public float restOffset;
  398. public ulong layer = 1;
  399. public CollisionReportMode collisionReportMode = CollisionReportMode.None;
  400. }
  401. }
  402. }