misc_fps.html 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js - platformer demo</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <style>
  8. body {
  9. background-color: rgb(200,200,200);
  10. margin: 0px;
  11. overflow: hidden;
  12. }
  13. #info {
  14. position: absolute;
  15. top: 0px; width: 100%;
  16. color: #ffffff;
  17. padding: 5px;
  18. font-family:Monospace;
  19. font-size:13px;
  20. font-weight: bold;
  21. text-align:center;
  22. }
  23. a {
  24. color: #ffffff;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <div id="info"><a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - platformer demo. cubemap by <a href="http://www.zfight.com/" target="_blank" rel="noopener">Jochum Skoglund</a>.<br />Use arrow keys to look around, WASD to move and SPACE to jump.</div>
  30. <script src="../build/three.js"></script>
  31. <script>
  32. // player motion parameters
  33. var motion = {
  34. airborne : false,
  35. position : new THREE.Vector3(), velocity : new THREE.Vector3(),
  36. rotation : new THREE.Vector2(), spinning : new THREE.Vector2()
  37. };
  38. motion.position.y = -150;
  39. // game systems code
  40. var resetPlayer = function() {
  41. if( motion.position.y < -123 ) {
  42. motion.position.set( -2, 7.7, 25 );
  43. motion.velocity.multiplyScalar( 0 );
  44. }
  45. };
  46. var keyboardControls = (function() {
  47. var keys = { SP : 32, W : 87, A : 65, S : 83, D : 68, UP : 38, LT : 37, DN : 40, RT : 39 };
  48. var keysPressed = {};
  49. (function( watchedKeyCodes ) {
  50. var handler = function( down ) {
  51. return function( e ) {
  52. var index = watchedKeyCodes.indexOf( e.keyCode );
  53. if( index >= 0 ) {
  54. keysPressed[watchedKeyCodes[index]] = down; e.preventDefault();
  55. }
  56. };
  57. };
  58. window.addEventListener( "keydown", handler( true ), false );
  59. window.addEventListener( "keyup", handler( false ), false );
  60. })([
  61. keys.SP, keys.W, keys.A, keys.S, keys.D, keys.UP, keys.LT, keys.DN, keys.RT
  62. ]);
  63. var forward = new THREE.Vector3();
  64. var sideways = new THREE.Vector3();
  65. return function() {
  66. if( !motion.airborne ) {
  67. // look around
  68. var sx = keysPressed[keys.UP] ? 0.03 : ( keysPressed[keys.DN] ? -0.03 : 0 );
  69. var sy = keysPressed[keys.LT] ? 0.03 : ( keysPressed[keys.RT] ? -0.03 : 0 );
  70. if( Math.abs( sx ) >= Math.abs( motion.spinning.x ) ) motion.spinning.x = sx;
  71. if( Math.abs( sy ) >= Math.abs( motion.spinning.y ) ) motion.spinning.y = sy;
  72. // move around
  73. forward.set( Math.sin( motion.rotation.y ), 0, Math.cos( motion.rotation.y ) );
  74. sideways.set( forward.z, 0, -forward.x );
  75. forward.multiplyScalar( keysPressed[keys.W] ? -0.1 : (keysPressed[keys.S] ? 0.1 : 0));
  76. sideways.multiplyScalar( keysPressed[keys.A] ? -0.1 : (keysPressed[keys.D] ? 0.1 : 0));
  77. var combined = forward.add( sideways );
  78. if( Math.abs( combined.x ) >= Math.abs( motion.velocity.x ) ) motion.velocity.x = combined.x;
  79. if( Math.abs( combined.y ) >= Math.abs( motion.velocity.y ) ) motion.velocity.y = combined.y;
  80. if( Math.abs( combined.z ) >= Math.abs( motion.velocity.z ) ) motion.velocity.z = combined.z;
  81. //jump
  82. var vy = keysPressed[keys.SP] ? 0.7 : 0;
  83. motion.velocity.y += vy;
  84. }
  85. };
  86. })();
  87. var jumpPads = (function() {
  88. var pads = [ new THREE.Vector3( -17.5, 8, -10 ), new THREE.Vector3( 17.5, 8, -10 ), new THREE.Vector3( 0, 8, 21 ) ];
  89. var temp = new THREE.Vector3();
  90. return function() {
  91. if( !motion.airborne ) {
  92. for( var j = 0, n = pads.length; j < n; j++ ) {
  93. if ( pads[j].distanceToSquared( motion.position ) < 2.3 ) {
  94. // calculate velocity towards another side of platform from jump pad position
  95. temp.copy( pads[j] ); temp.y = 0; temp.setLength( -0.8 ); temp.y = 0.7;
  96. motion.airborne = true; motion.velocity.copy( temp ); break;
  97. }
  98. }
  99. }
  100. };
  101. })();
  102. var applyPhysics = (function() {
  103. var timeStep = 5;
  104. var timeLeft = timeStep + 1;
  105. var birdsEye = 100;
  106. var kneeDeep = 0.4;
  107. var raycaster = new THREE.Raycaster();
  108. raycaster.ray.direction.set( 0, -1, 0 );
  109. var angles = new THREE.Vector2();
  110. var displacement = new THREE.Vector3();
  111. return function( dt ) {
  112. var platform = scene.getObjectByName( "platform", true );
  113. if( platform ) {
  114. timeLeft += dt;
  115. // run several fixed-step iterations to approximate varying-step
  116. dt = 5;
  117. while( timeLeft >= dt ) {
  118. var time = 0.3, damping = 0.93, gravity = 0.01, tau = 2 * Math.PI;
  119. raycaster.ray.origin.copy( motion.position );
  120. raycaster.ray.origin.y += birdsEye;
  121. var hits = raycaster.intersectObject( platform );
  122. motion.airborne = true;
  123. // are we above, or at most knee deep in, the platform?
  124. if( ( hits.length > 0 ) && ( hits[0].face.normal.y > 0 ) ) {
  125. var actualHeight = hits[0].distance - birdsEye;
  126. // collision: stick to the surface if landing on it
  127. if( ( motion.velocity.y <= 0 ) && ( Math.abs( actualHeight ) < kneeDeep ) ) {
  128. motion.position.y -= actualHeight;
  129. motion.velocity.y = 0;
  130. motion.airborne = false;
  131. }
  132. }
  133. if( motion.airborne ) motion.velocity.y -= gravity;
  134. angles.copy( motion.spinning ).multiplyScalar( time );
  135. if( !motion.airborne ) motion.spinning.multiplyScalar( damping );
  136. displacement.copy( motion.velocity ).multiplyScalar( time );
  137. if( !motion.airborne ) motion.velocity.multiplyScalar( damping );
  138. motion.rotation.add( angles );
  139. motion.position.add( displacement );
  140. // limit the tilt at ±0.4 radians
  141. motion.rotation.x = Math.max( -0.4, Math.min ( +0.4, motion.rotation.x ) );
  142. // wrap horizontal rotation to 0...2π
  143. motion.rotation.y += tau; motion.rotation.y %= tau;
  144. timeLeft -= dt;
  145. }
  146. }
  147. };
  148. })();
  149. var updateCamera = (function() {
  150. var euler = new THREE.Euler( 0, 0, 0, 'YXZ' );
  151. return function() {
  152. euler.x = motion.rotation.x;
  153. euler.y = motion.rotation.y;
  154. camera.quaternion.setFromEuler( euler );
  155. camera.position.copy( motion.position );
  156. camera.position.y += 3.0;
  157. };
  158. })();
  159. // init 3D stuff
  160. function makePlatform( jsonUrl, textureUrl, textureQuality ) {
  161. var placeholder = new THREE.Object3D();
  162. var texture = new THREE.TextureLoader().load( textureUrl );
  163. texture.minFilter = THREE.LinearFilter;
  164. texture.anisotropy = textureQuality;
  165. var loader = new THREE.JSONLoader();
  166. loader.load( jsonUrl, function( geometry ) {
  167. geometry.computeFaceNormals();
  168. var platform = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ map : texture }) );
  169. platform.name = "platform";
  170. placeholder.add( platform );
  171. });
  172. return placeholder;
  173. }
  174. var renderer = new THREE.WebGLRenderer( { antialias : true } );
  175. renderer.setPixelRatio( window.devicePixelRatio );
  176. document.body.appendChild( renderer.domElement );
  177. var camera = new THREE.PerspectiveCamera( 60, 1, 0.1, 9000 );
  178. var scene = new THREE.Scene();
  179. var envMap = new THREE.CubeTextureLoader().load( [
  180. 'textures/cube/skybox/px.jpg', // right
  181. 'textures/cube/skybox/nx.jpg', // left
  182. 'textures/cube/skybox/py.jpg', // top
  183. 'textures/cube/skybox/ny.jpg', // bottom
  184. 'textures/cube/skybox/pz.jpg', // back
  185. 'textures/cube/skybox/nz.jpg' // front
  186. ] );
  187. envMap.format = THREE.RGBFormat;
  188. scene.background = envMap;
  189. scene.add( makePlatform(
  190. 'models/platform/platform.json',
  191. 'models/platform/platform.jpg',
  192. renderer.capabilities.getMaxAnisotropy()
  193. ));
  194. // start the game
  195. var start = function( gameLoop, gameViewportSize ) {
  196. var resize = function() {
  197. var viewport = gameViewportSize();
  198. renderer.setSize( viewport.width, viewport.height );
  199. camera.aspect = viewport.width / viewport.height;
  200. camera.updateProjectionMatrix();
  201. };
  202. window.addEventListener( 'resize', resize, false );
  203. resize();
  204. var lastTimeStamp;
  205. var render = function( timeStamp ) {
  206. var timeElapsed = lastTimeStamp ? timeStamp - lastTimeStamp : 0; lastTimeStamp = timeStamp;
  207. // call our game loop with the time elapsed since last rendering, in ms
  208. gameLoop( timeElapsed );
  209. renderer.render( scene, camera );
  210. requestAnimationFrame( render );
  211. };
  212. requestAnimationFrame( render );
  213. };
  214. var gameLoop = function( dt ) {
  215. resetPlayer();
  216. keyboardControls();
  217. jumpPads();
  218. applyPhysics( dt );
  219. updateCamera();
  220. };
  221. var gameViewportSize = function() { return {
  222. width: window.innerWidth, height: window.innerHeight
  223. }};
  224. start( gameLoop, gameViewportSize );
  225. </script>
  226. </body>
  227. </html>