CannonSimpleCharacterController.re.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import * as RE from 'rogue-engine';
  2. import * as CANNON from 'cannon-es';
  3. import CannonBody from '../CannonBody.re';
  4. export default class CannonSimpleCharacterController extends RE.Component {
  5. @RE.props.num() fwdSpeed = 3;
  6. @RE.props.num() jumpSpeed = 5;
  7. rigidbody: CannonBody | undefined;
  8. canJump = false;
  9. private contactNormal = new CANNON.Vec3();
  10. private upAxis = new CANNON.Vec3(0, 1, 0);
  11. private inputAngularVelocity = new CANNON.Vec3();
  12. private inputVelocity = new CANNON.Vec3();
  13. awake() {
  14. this.rigidbody = RE.getComponent(CannonBody, this.object3d);
  15. // this.stick = RE.getComponent(TouchStick, this.object3d);
  16. this.rigidbody?.onCollide(event => {
  17. event.contact.ni.negate(this.contactNormal);
  18. if (this.contactNormal.dot(this.upAxis) > 0.5) {
  19. this.canJump = true
  20. }
  21. });
  22. if (!this.rigidbody) return;
  23. this.rigidbody.body.type = CANNON.Body.DYNAMIC;
  24. }
  25. update() {
  26. if (!this.rigidbody) return;
  27. this.inputVelocity.setZero();
  28. if (RE.Input.keyboard.getKeyPressed("KeyW")) {
  29. this.inputVelocity.z = -1;
  30. }
  31. else if (RE.Input.keyboard.getKeyPressed("KeyS")) {
  32. this.inputVelocity.z = 1;
  33. }
  34. else {
  35. this.inputVelocity.z = 0;
  36. }
  37. if (RE.Input.keyboard.getKeyPressed("KeyA")) {
  38. this.inputVelocity.x = -1;
  39. }
  40. else if (RE.Input.keyboard.getKeyPressed("KeyD")) {
  41. this.inputVelocity.x = 1;
  42. }
  43. else {
  44. this.inputVelocity.x = 0;
  45. }
  46. this.inputVelocity.normalize();
  47. this.inputVelocity.scale(this.fwdSpeed, this.inputVelocity);
  48. if (this.canJump && RE.Input.keyboard.getKeyDown("Space")) {
  49. this.rigidbody.body.velocity.y = this.jumpSpeed;
  50. this.canJump = false;
  51. }
  52. this.rigidbody.body.angularVelocity.y = this.inputAngularVelocity.y;
  53. this.rigidbody.body.vectorToWorldFrame(this.inputVelocity, this.inputVelocity);
  54. if (!this.canJump) return;
  55. this.rigidbody.body.velocity.x = this.inputVelocity.x;
  56. this.rigidbody.body.velocity.z = this.inputVelocity.z;
  57. }
  58. }
  59. RE.registerComponent(CannonSimpleCharacterController);