playerControllerComponent.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. MatrixF zRot;
  265. zRot.set(EulerF(0.0f, 0.0f, mOwner->getRotation().asEulerF().z));
  266. // Desired move direction & speed
  267. VectorF moveVec;
  268. F32 moveSpeed = mInputVelocity.len();
  269. zRot.getColumn(0, &moveVec);
  270. moveVec *= move->x;
  271. VectorF tv;
  272. zRot.getColumn(1, &tv);
  273. moveVec += tv * move->y;
  274. // Acceleration due to gravity
  275. VectorF acc(mPhysicsWorld->getGravity() * mGravityMod * TickSec);
  276. // Determine ground contact normal. Only look for contacts if
  277. // we can move and aren't mounted.
  278. mContactInfo.contactNormal = VectorF::Zero;
  279. mContactInfo.jump = false;
  280. mContactInfo.run = false;
  281. if (!mOwner->isMounted())
  282. findContact(&mContactInfo.run, &mContactInfo.jump, &mContactInfo.contactNormal);
  283. if (mContactInfo.jump)
  284. mJumpSurfaceNormal = mContactInfo.contactNormal;
  285. // If we don't have a runSurface but we do have a contactNormal,
  286. // then we are standing on something that is too steep.
  287. // Deflect the force of gravity by the normal so we slide.
  288. // We could also try aligning it to the runSurface instead,
  289. // but this seems to work well.
  290. if (!mContactInfo.run && !mContactInfo.contactNormal.isZero())
  291. acc = (acc - 2 * mContactInfo.contactNormal * mDot(acc, mContactInfo.contactNormal));
  292. // Acceleration on run surface
  293. if (mContactInfo.run && !mSwimming)
  294. {
  295. mContactTimer = 0;
  296. VectorF pv = moveVec;
  297. // Adjust the player's requested dir. to be parallel
  298. // to the contact surface.
  299. F32 pvl = pv.len();
  300. // Convert to acceleration
  301. if (pvl)
  302. pv *= moveSpeed / pvl;
  303. VectorF runAcc = pv - (mVelocity + acc);
  304. F32 runSpeed = runAcc.len();
  305. // Clamp acceleration, player also accelerates faster when
  306. // in his hard landing recover state.
  307. F32 maxAcc;
  308. maxAcc = (horizMaxAccel / mMass) * TickSec;
  309. if (runSpeed > maxAcc)
  310. runAcc *= maxAcc / runSpeed;
  311. acc += runAcc;
  312. }
  313. else if (!mSwimming && airControl > 0.0f)
  314. {
  315. VectorF pv;
  316. pv = moveVec;
  317. F32 pvl = pv.len();
  318. if (pvl)
  319. pv *= moveSpeed / pvl;
  320. VectorF runAcc = pv - (mVelocity + acc);
  321. runAcc.z = 0;
  322. runAcc.x = runAcc.x * airControl;
  323. runAcc.y = runAcc.y * airControl;
  324. F32 runSpeed = runAcc.len();
  325. // We don't test for sprinting when performing air control
  326. F32 maxAcc = (horizMaxAccel / mMass) * TickSec * 0.3f;
  327. if (runSpeed > maxAcc)
  328. runAcc *= maxAcc / runSpeed;
  329. acc += runAcc;
  330. // There are no special air control animations
  331. // so... increment this unless you really want to
  332. // play the run anims in the air.
  333. mContactTimer++;
  334. }
  335. else if (mSwimming)
  336. {
  337. // Remove acc into contact surface (should only be gravity)
  338. // Clear out floating point acc errors, this will allow
  339. // the player to "rest" on the ground.
  340. F32 vd = -mDot(acc, mContactInfo.contactNormal);
  341. if (vd > 0.0f)
  342. {
  343. VectorF dv = mContactInfo.contactNormal * (vd + 0.002f);
  344. acc += dv;
  345. if (acc.len() < 0.0001f)
  346. acc.set(0.0f, 0.0f, 0.0f);
  347. }
  348. // get the head pitch and add it to the moveVec
  349. // This more accurate swim vector calc comes from Matt Fairfax
  350. MatrixF xRot;
  351. xRot.set(EulerF(mOwner->getRotation().asEulerF().x, 0, 0));
  352. zRot.set(EulerF(0, 0, mOwner->getRotation().asEulerF().z));//reset prior uses
  353. MatrixF rot;
  354. rot.mul(zRot, xRot);
  355. rot.getColumn(0, &moveVec);
  356. moveVec *= move->x;
  357. rot.getColumn(1, &tv);//reset prior uses
  358. moveVec += tv * move->y;
  359. rot.getColumn(2, &tv);
  360. moveVec += tv * move->z;
  361. // Force a 0 move if there is no energy, and only drain
  362. // move energy if we're moving.
  363. VectorF swimVec = moveVec;
  364. // If we are swimming but close enough to the shore/ground
  365. // we can still have a surface-normal. In this case align the
  366. // velocity to the normal to make getting out of water easier.
  367. moveVec.normalize();
  368. F32 isSwimUp = mDot(moveVec, mContactInfo.contactNormal);
  369. if (!mContactInfo.contactNormal.isZero() && isSwimUp < 0.1f)
  370. {
  371. F32 pvl = swimVec.len();
  372. if (pvl)
  373. {
  374. VectorF nn;
  375. mCross(swimVec, VectorF(0.0f, 0.0f, 1.0f), &nn);
  376. nn *= 1.0f / pvl;
  377. VectorF cv = mContactInfo.contactNormal;
  378. cv -= nn * mDot(nn, cv);
  379. swimVec -= cv * mDot(swimVec, cv);
  380. }
  381. }
  382. F32 swimVecLen = swimVec.len();
  383. // Convert to acceleration.
  384. if (swimVecLen)
  385. swimVec *= moveSpeed / swimVecLen;
  386. VectorF swimAcc = swimVec - (mVelocity + acc);
  387. F32 swimSpeed = swimAcc.len();
  388. // Clamp acceleration.
  389. F32 maxAcc = (horizMaxAccel / mMass) * TickSec;
  390. if (swimSpeed > maxAcc)
  391. swimAcc *= maxAcc / swimSpeed;
  392. acc += swimAcc;
  393. mContactTimer++;
  394. }
  395. else
  396. mContactTimer++;
  397. // Add in force from physical zones...
  398. acc += (mOwner->getContainerInfo().appliedForce / mMass) * TickSec;
  399. // Adjust velocity with all the move & gravity acceleration
  400. // TG: I forgot why doesn't the TickSec multiply happen here...
  401. mVelocity += acc;
  402. // apply horizontal air resistance
  403. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  404. if (hvel > horizResistSpeed)
  405. {
  406. F32 speedCap = hvel;
  407. if (speedCap > horizMaxSpeed)
  408. speedCap = horizMaxSpeed;
  409. speedCap -= horizResistFactor * TickSec * (speedCap - horizResistSpeed);
  410. F32 scale = speedCap / hvel;
  411. mVelocity.x *= scale;
  412. mVelocity.y *= scale;
  413. }
  414. if (mVelocity.z > upResistSpeed)
  415. {
  416. if (mVelocity.z > upMaxSpeed)
  417. mVelocity.z = upMaxSpeed;
  418. mVelocity.z -= upResistFactor * TickSec * (mVelocity.z - upResistSpeed);
  419. }
  420. // Apply drag
  421. mVelocity -= mVelocity * mDrag * TickSec;
  422. // Clamp very small velocity to zero
  423. if (mVelocity.isZero())
  424. mVelocity = Point3F::Zero;
  425. // If we are not touching anything and have sufficient -z vel,
  426. // we are falling.
  427. if (mContactInfo.run)
  428. {
  429. mFalling = false;
  430. }
  431. else
  432. {
  433. VectorF vel;
  434. mOwner->getWorldToObj().mulV(mVelocity, &vel);
  435. mFalling = vel.z < fallingSpeedThreshold;
  436. }
  437. // Enter/Leave Liquid
  438. if (!mInWater && mOwner->getContainerInfo().waterCoverage > 0.0f)
  439. {
  440. mInWater = true;
  441. }
  442. else if (mInWater && mOwner->getContainerInfo().waterCoverage <= 0.0f)
  443. {
  444. mInWater = false;
  445. }
  446. }
  447. void PlayerControllerComponent::updatePos(const F32 travelTime)
  448. {
  449. if (!PHYSICSMGR)
  450. return;
  451. PROFILE_SCOPE(PlayerControllerComponent_UpdatePos);
  452. Point3F newPos;
  453. Collision col;
  454. dMemset(&col, 0, sizeof(col));
  455. static CollisionList collisionList;
  456. collisionList.clear();
  457. newPos = mPhysicsRep->move(mVelocity * travelTime, collisionList);
  458. bool haveCollisions = false;
  459. if (collisionList.getCount() > 0)
  460. {
  461. mFalling = false;
  462. haveCollisions = true;
  463. //TODO: clean this up so the phys component doesn't have to tell the col interface to do this
  464. CollisionInterface* colInterface = mOwner->getComponent<CollisionInterface>();
  465. if (colInterface)
  466. {
  467. colInterface->handleCollisionList(collisionList, mVelocity);
  468. }
  469. }
  470. if (haveCollisions)
  471. {
  472. // Pick the collision that most closely matches our direction
  473. VectorF velNormal = mVelocity;
  474. velNormal.normalizeSafe();
  475. const Collision *collision = &collisionList[0];
  476. F32 collisionDot = mDot(velNormal, collision->normal);
  477. const Collision *cp = collision + 1;
  478. const Collision *ep = collision + collisionList.getCount();
  479. for (; cp != ep; cp++)
  480. {
  481. F32 dp = mDot(velNormal, cp->normal);
  482. if (dp < collisionDot)
  483. {
  484. collisionDot = dp;
  485. collision = cp;
  486. }
  487. }
  488. // Modify our velocity based on collisions
  489. for (U32 i = 0; i<collisionList.getCount(); ++i)
  490. {
  491. F32 bd = -mDot(mVelocity, collisionList[i].normal);
  492. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  493. mVelocity += dv;
  494. }
  495. // Store the last collision for use later on. The handle collision
  496. // code only expects a single collision object.
  497. if (collisionList.getCount() > 0)
  498. col = collisionList[collisionList.getCount() - 1];
  499. // We'll handle any player-to-player collision, and the last collision
  500. // with other obejct types.
  501. for (U32 i = 0; i<collisionList.getCount(); ++i)
  502. {
  503. Collision& colCheck = collisionList[i];
  504. if (colCheck.object)
  505. {
  506. col = colCheck;
  507. }
  508. }
  509. }
  510. MatrixF newMat;
  511. newMat.setPosition(newPos);
  512. mPhysicsRep->setTransform(newMat);
  513. mOwner->setPosition(newPos);
  514. }
  515. //
  516. void PlayerControllerComponent::setVelocity(const VectorF& vel)
  517. {
  518. mVelocity = vel;
  519. // Clamp against the maximum velocity.
  520. if (mMaxVelocity > 0)
  521. {
  522. F32 len = mVelocity.magnitudeSafe();
  523. if (len > mMaxVelocity)
  524. {
  525. Point3F excess = mVelocity * (1.0f - (mMaxVelocity / len));
  526. mVelocity -= excess;
  527. }
  528. }
  529. setMaskBits(VelocityMask);
  530. }
  531. void PlayerControllerComponent::findContact(bool *run, bool *jump, VectorF *contactNormal)
  532. {
  533. SceneObject *contactObject = NULL;
  534. Vector<SceneObject*> overlapObjects;
  535. mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects);
  536. F32 vd = (*contactNormal).z;
  537. *run = vd > mCos(mDegToRad(moveSurfaceAngle));
  538. *jump = vd > mCos(mDegToRad(contactSurfaceAngle));
  539. // Check for triggers
  540. for (U32 i = 0; i < overlapObjects.size(); i++)
  541. {
  542. SceneObject *obj = overlapObjects[i];
  543. U32 objectMask = obj->getTypeMask();
  544. // Check: triggers, corpses and items...
  545. //
  546. if (objectMask & TriggerObjectType)
  547. {
  548. if (Trigger* pTrigger = dynamic_cast<Trigger*>(obj))
  549. {
  550. pTrigger->potentialEnterObject(mOwner);
  551. }
  552. else if (CollisionTrigger* pTriggerEx = dynamic_cast<CollisionTrigger*>(obj))
  553. {
  554. if (pTriggerEx)
  555. pTriggerEx->potentialEnterObject(mOwner);
  556. }
  557. //Add any other custom classes and the sort here that should be filtered against
  558. /*else if (TriggerExample* pTriggerEx = dynamic_cast<TriggerExample*>(obj))
  559. {
  560. if (pTriggerEx)
  561. pTriggerEx->potentialEnterObject(mOwner);
  562. }*/
  563. }
  564. }
  565. mContactInfo.contacted = contactObject != NULL;
  566. mContactInfo.contactObject = contactObject;
  567. if (mContactInfo.contacted)
  568. mContactInfo.contactNormal = *contactNormal;
  569. }
  570. void PlayerControllerComponent::applyImpulse(const Point3F &pos, const VectorF &vec)
  571. {
  572. AssertFatal(!mIsNaN(vec), "Player::applyImpulse() - The vector is NaN!");
  573. // Players ignore angular velocity
  574. VectorF vel;
  575. vel.x = vec.x / getMass();
  576. vel.y = vec.y / getMass();
  577. vel.z = vec.z / getMass();
  578. // Make sure the impulse isn't too bigg
  579. F32 len = vel.magnitudeSafe();
  580. if (len > sMaxImpulseVelocity)
  581. {
  582. Point3F excess = vel * (1.0f - (sMaxImpulseVelocity / len));
  583. vel -= excess;
  584. }
  585. setVelocity(mVelocity + vel);
  586. }
  587. DefineEngineMethod(PlayerControllerComponent, applyImpulse, bool, (Point3F pos, VectorF vel), ,
  588. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  589. "@param pos impulse world position\n"
  590. "@param vel impulse velocity (impulse force F = m * v)\n"
  591. "@return Always true\n"
  592. "@note Not all objects that derrive from GameBase have this defined.\n")
  593. {
  594. object->applyImpulse(pos, vel);
  595. return true;
  596. }
  597. DefineEngineMethod(PlayerControllerComponent, getContactNormal, Point3F, (), ,
  598. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  599. "@param pos impulse world position\n"
  600. "@param vel impulse velocity (impulse force F = m * v)\n"
  601. "@return Always true\n"
  602. "@note Not all objects that derrive from GameBase have this defined.\n")
  603. {
  604. return object->getContactNormal();
  605. }
  606. DefineEngineMethod(PlayerControllerComponent, getContactObject, SceneObject*, (), ,
  607. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  608. "@param pos impulse world position\n"
  609. "@param vel impulse velocity (impulse force F = m * v)\n"
  610. "@return Always true\n"
  611. "@note Not all objects that derrive from GameBase have this defined.\n")
  612. {
  613. return object->getContactObject();
  614. }
  615. DefineEngineMethod(PlayerControllerComponent, isContacted, bool, (), ,
  616. "@brief Apply an impulse to this object as defined by a world position and velocity vector.\n\n"
  617. "@param pos impulse world position\n"
  618. "@param vel impulse velocity (impulse force F = m * v)\n"
  619. "@return Always true\n"
  620. "@note Not all objects that derrive from GameBase have this defined.\n")
  621. {
  622. return object->isContacted();
  623. }