playerControllerComponent.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "T3D/components/physics/playerControllerComponent.h"
  23. #include "platform/platform.h"
  24. #include "console/consoleTypes.h"
  25. #include "core/util/safeDelete.h"
  26. #include "core/resourceManager.h"
  27. #include "core/stream/fileStream.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/consoleObject.h"
  30. #include "ts/tsShapeInstance.h"
  31. #include "core/stream/bitStream.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "console/engineAPI.h"
  34. #include "lighting/lightQuery.h"
  35. #include "T3D/gameBase/gameConnection.h"
  36. #include "collision/collision.h"
  37. #include "T3D/physics/physicsPlayer.h"
  38. #include "T3D/physics/physicsPlugin.h"
  39. #include "T3D/components/collision/collisionInterfaces.h"
  40. #include "T3D/trigger.h"
  41. #include "T3D/components/collision/collisionTrigger.h"
  42. // Movement constants
  43. static F32 sVerticalStepDot = 0.173f; // 80
  44. static F32 sMinFaceDistance = 0.01f;
  45. static F32 sTractionDistance = 0.04f;
  46. static F32 sNormalElasticity = 0.01f;
  47. static U32 sMoveRetryCount = 5;
  48. static F32 sMaxImpulseVelocity = 200.0f;
  49. //////////////////////////////////////////////////////////////////////////
  50. // Callbacks
  51. IMPLEMENT_CALLBACK(PlayerControllerComponent, updateMove, void, (PlayerControllerComponent* obj), (obj),
  52. "Called when the player updates it's movement, only called if object is set to callback in script(doUpdateMove).\n"
  53. "@param obj the Player object\n");
  54. //////////////////////////////////////////////////////////////////////////
  55. // Constructor/Destructor
  56. //////////////////////////////////////////////////////////////////////////
  57. PlayerControllerComponent::PlayerControllerComponent() : Component()
  58. {
  59. addComponentField("isStatic", "If enabled, object will not simulate physics", "bool", "0", "");
  60. addComponentField("gravity", "The direction of gravity affecting this object, as a vector", "vector", "0 0 -9", "");
  61. addComponentField("drag", "The drag coefficient that constantly affects the object", "float", "0.7", "");
  62. addComponentField("mass", "The mass of the object", "float", "1", "");
  63. mBuoyancy = 0.f;
  64. mFriction = 0.3f;
  65. mElasticity = 0.4f;
  66. mMaxVelocity = 3000.f;
  67. mVelocity = VectorF::Zero;
  68. mContactTimer = 0;
  69. mSticky = false;
  70. mFalling = false;
  71. mSwimming = false;
  72. mInWater = false;
  73. mDelta.pos = mDelta.posVec = Point3F::Zero;
  74. mDelta.warpTicks = mDelta.warpCount = 0;
  75. mDelta.rot[0].identity();
  76. mDelta.rot[1].identity();
  77. mDelta.dt = 1;
  78. mUseDirectMoveInput = false;
  79. mFriendlyName = "Player Controller";
  80. mComponentType = "Physics";
  81. mDescription = getDescriptionText("A general-purpose physics player controller.");
  82. //mNetFlags.set(Ghostable | ScopeAlways);
  83. mMass = 9.0f; // from ShapeBase
  84. mDrag = 1.0f; // from ShapeBase
  85. maxStepHeight = 1.0f;
  86. moveSurfaceAngle = 60.0f;
  87. contactSurfaceAngle = 85.0f;
  88. fallingSpeedThreshold = -10.0f;
  89. horizMaxSpeed = 80.0f;
  90. horizMaxAccel = 100.0f;
  91. horizResistSpeed = 38.0f;
  92. horizResistFactor = 1.0f;
  93. upMaxSpeed = 80.0f;
  94. upMaxAccel = 100.0f;
  95. upResistSpeed = 38.0f;
  96. upResistFactor = 1.0f;
  97. // Air control
  98. airControl = 0.0f;
  99. //Grav mod
  100. mGravityMod = 1;
  101. mInputVelocity = Point3F(0, 0, 0);
  102. mPhysicsRep = nullptr;
  103. mPhysicsWorld = nullptr;
  104. mOwnerCollisionInterface = nullptr;
  105. mIntegrationCount = 0;
  106. }
  107. PlayerControllerComponent::~PlayerControllerComponent()
  108. {
  109. for (S32 i = 0; i < mFields.size(); ++i)
  110. {
  111. ComponentField &field = mFields[i];
  112. SAFE_DELETE_ARRAY(field.mFieldDescription);
  113. }
  114. SAFE_DELETE_ARRAY(mDescription);
  115. }
  116. IMPLEMENT_CO_NETOBJECT_V1(PlayerControllerComponent);
  117. //////////////////////////////////////////////////////////////////////////
  118. bool PlayerControllerComponent::onAdd()
  119. {
  120. if (!Parent::onAdd())
  121. return false;
  122. return true;
  123. }
  124. void PlayerControllerComponent::onRemove()
  125. {
  126. Parent::onRemove();
  127. SAFE_DELETE(mPhysicsRep);
  128. }
  129. void PlayerControllerComponent::onComponentAdd()
  130. {
  131. Parent::onComponentAdd();
  132. updatePhysics();
  133. }
  134. void PlayerControllerComponent::componentAddedToOwner(Component *comp)
  135. {
  136. if (comp->getId() == getId())
  137. return;
  138. //test if this is a shape component!
  139. CollisionInterface *collisionInterface = dynamic_cast<CollisionInterface*>(comp);
  140. if (collisionInterface)
  141. {
  142. collisionInterface->onCollisionChanged.notify(this, &PlayerControllerComponent::updatePhysics);
  143. mOwnerCollisionInterface = collisionInterface;
  144. updatePhysics();
  145. }
  146. }
  147. void PlayerControllerComponent::componentRemovedFromOwner(Component *comp)
  148. {
  149. if (comp->getId() == getId()) //?????????
  150. return;
  151. //test if this is a shape component!
  152. CollisionInterface *collisionInterface = dynamic_cast<CollisionInterface*>(comp);
  153. if (collisionInterface)
  154. {
  155. collisionInterface->onCollisionChanged.remove(this, &PlayerControllerComponent::updatePhysics);
  156. mOwnerCollisionInterface = NULL;
  157. updatePhysics();
  158. }
  159. }
  160. void PlayerControllerComponent::updatePhysics(PhysicsCollision *collision)
  161. {
  162. if (!PHYSICSMGR)
  163. return;
  164. mPhysicsWorld = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client");
  165. //first, clear the old physRep
  166. SAFE_DELETE(mPhysicsRep);
  167. mPhysicsRep = PHYSICSMGR->createPlayer();
  168. F32 runSurfaceCos = mCos(mDegToRad(moveSurfaceAngle));
  169. Point3F ownerBounds = mOwner->getObjBox().getExtents() * mOwner->getScale();
  170. mPhysicsRep->init("", ownerBounds, runSurfaceCos, maxStepHeight, mOwner, mPhysicsWorld);
  171. mPhysicsRep->setTransform(mOwner->getTransform());
  172. }
  173. void PlayerControllerComponent::initPersistFields()
  174. {
  175. Parent::initPersistFields();
  176. addField("inputVelocity", TypePoint3F, Offset(mInputVelocity, PlayerControllerComponent), "");
  177. addField("useDirectMoveInput", TypePoint3F, Offset(mUseDirectMoveInput, PlayerControllerComponent), "");
  178. }
  179. U32 PlayerControllerComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  180. {
  181. U32 retMask = Parent::packUpdate(con, mask, stream);
  182. return retMask;
  183. }
  184. void PlayerControllerComponent::unpackUpdate(NetConnection *con, BitStream *stream)
  185. {
  186. Parent::unpackUpdate(con, stream);
  187. }
  188. //
  189. void PlayerControllerComponent::processTick()
  190. {
  191. Parent::processTick();
  192. if (!isServerObject() || !isActive())
  193. return;
  194. // Warp to catch up to server
  195. if (mDelta.warpCount < mDelta.warpTicks)
  196. {
  197. mDelta.warpCount++;
  198. // Set new pos.
  199. mDelta.pos = mOwner->getPosition();
  200. mDelta.pos += mDelta.warpOffset;
  201. mDelta.rot[0] = mDelta.rot[1];
  202. mDelta.rot[1].interpolate(mDelta.warpRot[0], mDelta.warpRot[1], F32(mDelta.warpCount) / mDelta.warpTicks);
  203. MatrixF trans;
  204. mDelta.rot[1].setMatrix(&trans);
  205. trans.setPosition(mDelta.pos);
  206. mOwner->setTransform(trans);
  207. // Pos backstepping
  208. mDelta.posVec.x = -mDelta.warpOffset.x;
  209. mDelta.posVec.y = -mDelta.warpOffset.y;
  210. mDelta.posVec.z = -mDelta.warpOffset.z;
  211. }
  212. else
  213. {
  214. // Save current rigid state interpolation
  215. mDelta.posVec = mOwner->getPosition();
  216. mDelta.rot[0] = mOwner->getTransform();
  217. updateMove();
  218. updatePos(TickSec);
  219. // Wrap up interpolation info
  220. mDelta.pos = mOwner->getPosition();
  221. mDelta.posVec -= mOwner->getPosition();
  222. mDelta.rot[1] = mOwner->getTransform();
  223. // Update container database
  224. setTransform(mOwner->getTransform());
  225. setMaskBits(VelocityMask);
  226. setMaskBits(PositionMask);
  227. }
  228. }
  229. void PlayerControllerComponent::interpolateTick(F32 dt)
  230. {
  231. }
  232. void PlayerControllerComponent::ownerTransformSet(MatrixF *mat)
  233. {
  234. if (mPhysicsRep)
  235. mPhysicsRep->setTransform(mOwner->getTransform());
  236. }
  237. void PlayerControllerComponent::setTransform(const MatrixF& mat)
  238. {
  239. mOwner->setTransform(mat);
  240. setMaskBits(UpdateMask);
  241. }
  242. //
  243. void PlayerControllerComponent::updateMove()
  244. {
  245. if (!PHYSICSMGR)
  246. return;
  247. Move *move = &mOwner->lastMove;
  248. //If we're not set to use mUseDirectMoveInput, then we allow for an override in the form of mInputVelocity
  249. if (!mUseDirectMoveInput)
  250. {
  251. move->x = mInputVelocity.x;
  252. move->y = mInputVelocity.y;
  253. move->z = mInputVelocity.z;
  254. }
  255. // Is waterCoverage high enough to be 'swimming'?
  256. {
  257. bool swimming = mOwner->getContainerInfo().waterCoverage > 0.65f/* && canSwim()*/;
  258. if (swimming != mSwimming)
  259. {
  260. mSwimming = swimming;
  261. }
  262. }
  263. // Update current orientation
  264. bool doStandardMove = true;
  265. GameConnection* con = mOwner->getControllingClient();
  266. MatrixF zRot;
  267. zRot.set(EulerF(0.0f, 0.0f, mOwner->getRotation().asEulerF().z));
  268. // Desired move direction & speed
  269. VectorF moveVec;
  270. F32 moveSpeed = mInputVelocity.len();
  271. zRot.getColumn(0, &moveVec);
  272. moveVec *= move->x;
  273. VectorF tv;
  274. zRot.getColumn(1, &tv);
  275. moveVec += tv * move->y;
  276. // Acceleration due to gravity
  277. VectorF acc(mPhysicsWorld->getGravity() * mGravityMod * TickSec);
  278. // Determine ground contact normal. Only look for contacts if
  279. // we can move and aren't mounted.
  280. mContactInfo.contactNormal = VectorF::Zero;
  281. mContactInfo.jump = false;
  282. mContactInfo.run = false;
  283. bool jumpSurface = false, runSurface = false;
  284. if (!mOwner->isMounted())
  285. findContact(&mContactInfo.run, &mContactInfo.jump, &mContactInfo.contactNormal);
  286. if (mContactInfo.jump)
  287. mJumpSurfaceNormal = mContactInfo.contactNormal;
  288. // If we don't have a runSurface but we do have a contactNormal,
  289. // then we are standing on something that is too steep.
  290. // Deflect the force of gravity by the normal so we slide.
  291. // We could also try aligning it to the runSurface instead,
  292. // but this seems to work well.
  293. if (!mContactInfo.run && !mContactInfo.contactNormal.isZero())
  294. acc = (acc - 2 * mContactInfo.contactNormal * mDot(acc, mContactInfo.contactNormal));
  295. // Acceleration on run surface
  296. if (mContactInfo.run && !mSwimming)
  297. {
  298. mContactTimer = 0;
  299. VectorF pv = moveVec;
  300. // Adjust the player's requested dir. to be parallel
  301. // to the contact surface.
  302. F32 pvl = pv.len();
  303. // Convert to acceleration
  304. if (pvl)
  305. pv *= moveSpeed / pvl;
  306. VectorF runAcc = pv - (mVelocity + acc);
  307. F32 runSpeed = runAcc.len();
  308. // Clamp acceleration, player also accelerates faster when
  309. // in his hard landing recover state.
  310. F32 maxAcc;
  311. maxAcc = (horizMaxAccel / mMass) * TickSec;
  312. if (runSpeed > maxAcc)
  313. runAcc *= maxAcc / runSpeed;
  314. acc += runAcc;
  315. }
  316. else if (!mSwimming && airControl > 0.0f)
  317. {
  318. VectorF pv;
  319. pv = moveVec;
  320. F32 pvl = pv.len();
  321. if (pvl)
  322. pv *= moveSpeed / pvl;
  323. VectorF runAcc = pv - (mVelocity + acc);
  324. runAcc.z = 0;
  325. runAcc.x = runAcc.x * airControl;
  326. runAcc.y = runAcc.y * airControl;
  327. F32 runSpeed = runAcc.len();
  328. // We don't test for sprinting when performing air control
  329. F32 maxAcc = (horizMaxAccel / mMass) * TickSec * 0.3f;
  330. if (runSpeed > maxAcc)
  331. runAcc *= maxAcc / runSpeed;
  332. acc += runAcc;
  333. // There are no special air control animations
  334. // so... increment this unless you really want to
  335. // play the run anims in the air.
  336. mContactTimer++;
  337. }
  338. else if (mSwimming)
  339. {
  340. // Remove acc into contact surface (should only be gravity)
  341. // Clear out floating point acc errors, this will allow
  342. // the player to "rest" on the ground.
  343. F32 vd = -mDot(acc, mContactInfo.contactNormal);
  344. if (vd > 0.0f)
  345. {
  346. VectorF dv = mContactInfo.contactNormal * (vd + 0.002f);
  347. acc += dv;
  348. if (acc.len() < 0.0001f)
  349. acc.set(0.0f, 0.0f, 0.0f);
  350. }
  351. // get the head pitch and add it to the moveVec
  352. // This more accurate swim vector calc comes from Matt Fairfax
  353. MatrixF xRot;
  354. xRot.set(EulerF(mOwner->getRotation().asEulerF().x, 0, 0));
  355. zRot.set(EulerF(0, 0, mOwner->getRotation().asEulerF().z));//reset prior uses
  356. MatrixF rot;
  357. rot.mul(zRot, xRot);
  358. rot.getColumn(0, &moveVec);
  359. moveVec *= move->x;
  360. rot.getColumn(1, &tv);//reset prior uses
  361. moveVec += tv * move->y;
  362. rot.getColumn(2, &tv);
  363. moveVec += tv * move->z;
  364. // Force a 0 move if there is no energy, and only drain
  365. // move energy if we're moving.
  366. VectorF swimVec = moveVec;
  367. // If we are swimming but close enough to the shore/ground
  368. // we can still have a surface-normal. In this case align the
  369. // velocity to the normal to make getting out of water easier.
  370. moveVec.normalize();
  371. F32 isSwimUp = mDot(moveVec, mContactInfo.contactNormal);
  372. if (!mContactInfo.contactNormal.isZero() && isSwimUp < 0.1f)
  373. {
  374. F32 pvl = swimVec.len();
  375. if (pvl)
  376. {
  377. VectorF nn;
  378. mCross(swimVec, VectorF(0.0f, 0.0f, 1.0f), &nn);
  379. nn *= 1.0f / pvl;
  380. VectorF cv = mContactInfo.contactNormal;
  381. cv -= nn * mDot(nn, cv);
  382. swimVec -= cv * mDot(swimVec, cv);
  383. }
  384. }
  385. F32 swimVecLen = swimVec.len();
  386. // Convert to acceleration.
  387. if (swimVecLen)
  388. swimVec *= moveSpeed / swimVecLen;
  389. VectorF swimAcc = swimVec - (mVelocity + acc);
  390. F32 swimSpeed = swimAcc.len();
  391. // Clamp acceleration.
  392. F32 maxAcc = (horizMaxAccel / mMass) * TickSec;
  393. if (swimSpeed > maxAcc)
  394. swimAcc *= maxAcc / swimSpeed;
  395. acc += swimAcc;
  396. mContactTimer++;
  397. }
  398. else
  399. mContactTimer++;
  400. // Add in force from physical zones...
  401. acc += (mOwner->getContainerInfo().appliedForce / mMass) * TickSec;
  402. // Adjust velocity with all the move & gravity acceleration
  403. // TG: I forgot why doesn't the TickSec multiply happen here...
  404. mVelocity += acc;
  405. // apply horizontal air resistance
  406. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  407. if (hvel > horizResistSpeed)
  408. {
  409. F32 speedCap = hvel;
  410. if (speedCap > horizMaxSpeed)
  411. speedCap = horizMaxSpeed;
  412. speedCap -= horizResistFactor * TickSec * (speedCap - horizResistSpeed);
  413. F32 scale = speedCap / hvel;
  414. mVelocity.x *= scale;
  415. mVelocity.y *= scale;
  416. }
  417. if (mVelocity.z > upResistSpeed)
  418. {
  419. if (mVelocity.z > upMaxSpeed)
  420. mVelocity.z = upMaxSpeed;
  421. mVelocity.z -= upResistFactor * TickSec * (mVelocity.z - upResistSpeed);
  422. }
  423. // Apply drag
  424. mVelocity -= mVelocity * mDrag * TickSec;
  425. // Clamp very small velocity to zero
  426. if (mVelocity.isZero())
  427. mVelocity = Point3F::Zero;
  428. // If we are not touching anything and have sufficient -z vel,
  429. // we are falling.
  430. if (mContactInfo.run)
  431. {
  432. mFalling = false;
  433. }
  434. else
  435. {
  436. VectorF vel;
  437. mOwner->getWorldToObj().mulV(mVelocity, &vel);
  438. mFalling = vel.z < fallingSpeedThreshold;
  439. }
  440. // Enter/Leave Liquid
  441. if (!mInWater && mOwner->getContainerInfo().waterCoverage > 0.0f)
  442. {
  443. mInWater = true;
  444. }
  445. else if (mInWater && mOwner->getContainerInfo().waterCoverage <= 0.0f)
  446. {
  447. mInWater = false;
  448. }
  449. }
  450. void PlayerControllerComponent::updatePos(const F32 travelTime)
  451. {
  452. if (!PHYSICSMGR)
  453. return;
  454. PROFILE_SCOPE(PlayerControllerComponent_UpdatePos);
  455. Point3F newPos;
  456. Collision col;
  457. dMemset(&col, 0, sizeof(col));
  458. static CollisionList collisionList;
  459. collisionList.clear();
  460. newPos = mPhysicsRep->move(mVelocity * travelTime, collisionList);
  461. bool haveCollisions = false;
  462. bool wasFalling = mFalling;
  463. if (collisionList.getCount() > 0)
  464. {
  465. mFalling = false;
  466. haveCollisions = true;
  467. //TODO: clean this up so the phys component doesn't have to tell the col interface to do this
  468. CollisionInterface* colInterface = mOwner->getComponent<CollisionInterface>();
  469. if (colInterface)
  470. {
  471. colInterface->handleCollisionList(collisionList, mVelocity);
  472. }
  473. }
  474. if (haveCollisions)
  475. {
  476. // Pick the collision that most closely matches our direction
  477. VectorF velNormal = mVelocity;
  478. velNormal.normalizeSafe();
  479. const Collision *collision = &collisionList[0];
  480. F32 collisionDot = mDot(velNormal, collision->normal);
  481. const Collision *cp = collision + 1;
  482. const Collision *ep = collision + collisionList.getCount();
  483. for (; cp != ep; cp++)
  484. {
  485. F32 dp = mDot(velNormal, cp->normal);
  486. if (dp < collisionDot)
  487. {
  488. collisionDot = dp;
  489. collision = cp;
  490. }
  491. }
  492. // Modify our velocity based on collisions
  493. for (U32 i = 0; i<collisionList.getCount(); ++i)
  494. {
  495. F32 bd = -mDot(mVelocity, collisionList[i].normal);
  496. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  497. mVelocity += dv;
  498. }
  499. // Store the last collision for use later on. The handle collision
  500. // code only expects a single collision object.
  501. if (collisionList.getCount() > 0)
  502. col = collisionList[collisionList.getCount() - 1];
  503. // We'll handle any player-to-player collision, and the last collision
  504. // with other obejct types.
  505. for (U32 i = 0; i<collisionList.getCount(); ++i)
  506. {
  507. Collision& colCheck = collisionList[i];
  508. if (colCheck.object)
  509. {
  510. col = colCheck;
  511. }
  512. }
  513. }
  514. MatrixF newMat;
  515. newMat.setPosition(newPos);
  516. mPhysicsRep->setTransform(newMat);
  517. mOwner->setPosition(newPos);
  518. }
  519. //
  520. void PlayerControllerComponent::setVelocity(const VectorF& vel)
  521. {
  522. mVelocity = vel;
  523. // Clamp against the maximum velocity.
  524. if (mMaxVelocity > 0)
  525. {
  526. F32 len = mVelocity.magnitudeSafe();
  527. if (len > mMaxVelocity)
  528. {
  529. Point3F excess = mVelocity * (1.0f - (mMaxVelocity / len));
  530. mVelocity -= excess;
  531. }
  532. }
  533. setMaskBits(VelocityMask);
  534. }
  535. void PlayerControllerComponent::findContact(bool *run, bool *jump, VectorF *contactNormal)
  536. {
  537. SceneObject *contactObject = NULL;
  538. Vector<SceneObject*> overlapObjects;
  539. mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects);
  540. F32 vd = (*contactNormal).z;
  541. *run = vd > mCos(mDegToRad(moveSurfaceAngle));
  542. *jump = vd > mCos(mDegToRad(contactSurfaceAngle));
  543. // Check for triggers
  544. for (U32 i = 0; i < overlapObjects.size(); i++)
  545. {
  546. SceneObject *obj = overlapObjects[i];
  547. U32 objectMask = obj->getTypeMask();
  548. // Check: triggers, corpses and items...
  549. //
  550. if (objectMask & TriggerObjectType)
  551. {
  552. if (Trigger* pTrigger = dynamic_cast<Trigger*>(obj))
  553. {
  554. pTrigger->potentialEnterObject(mOwner);
  555. }
  556. else if (CollisionTrigger* pTriggerEx = dynamic_cast<CollisionTrigger*>(obj))
  557. {
  558. if (pTriggerEx)
  559. pTriggerEx->potentialEnterObject(mOwner);
  560. }
  561. //Add any other custom classes and the sort here that should be filtered against
  562. /*else if (TriggerExample* pTriggerEx = dynamic_cast<TriggerExample*>(obj))
  563. {
  564. if (pTriggerEx)
  565. pTriggerEx->potentialEnterObject(mOwner);
  566. }*/
  567. }
  568. }
  569. mContactInfo.contacted = contactObject != NULL;
  570. mContactInfo.contactObject = contactObject;
  571. if (mContactInfo.contacted)
  572. mContactInfo.contactNormal = *contactNormal;
  573. }
  574. void PlayerControllerComponent::applyImpulse(const Point3F &pos, const VectorF &vec)
  575. {
  576. AssertFatal(!mIsNaN(vec), "Player::applyImpulse() - The vector is NaN!");
  577. // Players ignore angular velocity
  578. VectorF vel;
  579. vel.x = vec.x / getMass();
  580. vel.y = vec.y / getMass();
  581. vel.z = vec.z / getMass();
  582. // Make sure the impulse isn't too bigg
  583. F32 len = vel.magnitudeSafe();
  584. if (len > sMaxImpulseVelocity)
  585. {
  586. Point3F excess = vel * (1.0f - (sMaxImpulseVelocity / len));
  587. vel -= excess;
  588. }
  589. setVelocity(mVelocity + vel);
  590. }
  591. DefineEngineMethod(PlayerControllerComponent, applyImpulse, bool, (Point3F pos, VectorF vel), ,
  592. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  593. "@param pos impulse world position\n"
  594. "@param vel impulse velocity (impulse force F = m * v)\n"
  595. "@return Always true\n"
  596. "@note Not all objects that derrive from GameBase have this defined.\n")
  597. {
  598. object->applyImpulse(pos, vel);
  599. return true;
  600. }
  601. DefineEngineMethod(PlayerControllerComponent, getContactNormal, Point3F, (), ,
  602. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  603. "@param pos impulse world position\n"
  604. "@param vel impulse velocity (impulse force F = m * v)\n"
  605. "@return Always true\n"
  606. "@note Not all objects that derrive from GameBase have this defined.\n")
  607. {
  608. return object->getContactNormal();
  609. }
  610. DefineEngineMethod(PlayerControllerComponent, getContactObject, SceneObject*, (), ,
  611. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  612. "@param pos impulse world position\n"
  613. "@param vel impulse velocity (impulse force F = m * v)\n"
  614. "@return Always true\n"
  615. "@note Not all objects that derrive from GameBase have this defined.\n")
  616. {
  617. return object->getContactObject();
  618. }
  619. DefineEngineMethod(PlayerControllerComponent, isContacted, bool, (), ,
  620. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  621. "@param pos impulse world position\n"
  622. "@param vel impulse velocity (impulse force F = m * v)\n"
  623. "@return Always true\n"
  624. "@note Not all objects that derrive from GameBase have this defined.\n")
  625. {
  626. return object->isContacted();
  627. }