UNPKG

three-game-engine

Version:

Simple light-weight game engine using three.js, three-mesh-ui and rapier

73 lines (72 loc) 3.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const THREE = require("three"); const rapier3d_compat_1 = require("@dimforge/rapier3d-compat"); const GameObject_1 = require("../GameObject"); const RigidBodyComponent_1 = require("../components/RigidBodyComponent"); const defaultControllerOptions = { walkingSpeed: 2, runningSpeed: 4, jumpCooldown: 1000 }; class CharacterController extends GameObject_1.default { constructor(parent, options, controllerOptions = defaultControllerOptions) { super(parent, { ...options // merge with any passed in GameObjectOptions }); this.lastJumpTime = 0; this.controllerOptions = Object.assign({}, defaultControllerOptions, controllerOptions); this.lastJumpTime = 0; } afterLoaded() { } getDesiredYaw() { const inputManager = this.getScene().game.inputManager; const mouse = inputManager.mouseHandler; return mouse.getPointerX() / -250.0; } getDesiredPitch() { const inputManager = this.getScene().game.inputManager; const mouse = inputManager.mouseHandler; return mouse.getPointerY() / -250.0; } getDesiredTranslation(deltaTimeInSec) { const inputManager = this.getScene().game.inputManager; const keyboard = inputManager.keyboardHandler; // meters per sec const movementSpeed = keyboard.isShiftDown() ? this.controllerOptions.runningSpeed : this.controllerOptions.walkingSpeed; const movementAmount = movementSpeed * deltaTimeInSec; const desiredMovement = { x: 0, y: 0, z: 0 }; const verticalAmount = inputManager.readVerticalAxis(); desiredMovement.z += verticalAmount; const horizontalAmount = inputManager.readHorizontalAxis(); desiredMovement.x += horizontalAmount; const desiredMovementVector = new THREE.Vector3(desiredMovement.x, desiredMovement.y, desiredMovement.z); desiredMovementVector.normalize(); desiredMovementVector.multiplyScalar(movementAmount); return desiredMovementVector; } beforeRender({ deltaTimeInSec, time }) { } rayCastToGround() { const rapierWorld = this.getScene().getRapierWorld(); const rigidBodyComponent = this.getComponent(RigidBodyComponent_1.default); const rapierRigidBody = rigidBodyComponent.getRapierRigidBody(); const currentPosition = rapierRigidBody.translation(); const capsuleHalfHeight = 0.45 + 0.4; //this.controllerOptions.capsule.halfHeight - this.controllerOptions.capsule.radius // Point just below the capsulate collider const rayOrigin = { x: currentPosition.x, y: currentPosition.y - capsuleHalfHeight - 0.01, z: currentPosition.z }; const rayDirection = { x: 0, y: -1, z: 0 }; // downwards const ray = new rapier3d_compat_1.default.Ray(rayOrigin, rayDirection); return rapierWorld.castRay(ray, 1, true); } isOnGround(threshold = 0.3) { const groundHit = this.rayCastToGround(); return groundHit ? groundHit.toi < threshold : false; } } exports.default = CharacterController;