1 tQuery.registerStatic('createMinecraftCharKeyboard2', function(opts){ 2 return new tQuery.MinecraftCharKeyboard2(opts) 3 }); 4 5 tQuery.registerStatic('MinecraftCharKeyboard2', function(opts){ 6 // handle polymorphism 7 if( opts instanceof THREE.Object3D ) opts = { object3D: opts }; 8 if( opts instanceof tQuery.Object3D ) opts = { object3D: opts.get(0) }; 9 if( opts.object3D instanceof tQuery.Object3D ) opts.object3D = opts.object3D.get(0) 10 // handle default values 11 opts = this._opts = tQuery.extend(opts, { 12 world : tQuery.world, 13 lateralMove : 'strafe' 14 }); 15 // sanity check 16 console.assert( opts.object3D instanceof THREE.Object3D ) 17 console.assert( ['strafe', 'rotationY'].indexOf(opts.lateralMove) !== -1 ); 18 19 // init some variable 20 var midiKey = new tQuery.MidiKeyTween(); 21 // just debug 22 // world.loop().hook(function(delta, now){ 23 // console.log("state", midiKey.state(), 'value', midiKey.value()) 24 // }); 25 // user control 26 this._$onLoop = opts.world.loop().hook(function(delta, now){ 27 var keyboard = tQuery.keyboard(); 28 var model = opts.object3D; 29 var action = { 30 left : keyboard.pressed("left") || keyboard.pressed("a") || keyboard.pressed("a"), 31 right : keyboard.pressed("right") || keyboard.pressed("d"), 32 up : keyboard.pressed("up") || keyboard.pressed("w") || keyboard.pressed("z"), 33 down : keyboard.pressed("down") || keyboard.pressed("s"), 34 }; 35 // keyboard handling 36 if( opts.lateralMove === 'rotationY' ){ 37 // lateral => rotation Y 38 if( action.left ) model.rotation.y += 0.3 * delta * Math.PI * 2; 39 if( action.right ) model.rotation.y -= 0.3 * delta * Math.PI * 2; 40 }else if( opts.lateralMove === 'strafe' ){ 41 // lateral => strafe 42 var distance = 0; 43 if( action.left ) distance = +2 * delta; 44 if( action.right ) distance = -2 * delta; 45 if( distance ){ 46 var speed = new THREE.Vector3(distance, 0, 0); 47 var matrix = new THREE.Matrix4().makeRotationY(model.rotation.y); 48 matrix.multiplyVector3(speed); 49 model.position.addSelf(speed); 50 } 51 }else console.assert(false, 'opts.lateralMove invalid: '+opts.lateralMove); 52 53 var distance = 0; 54 if( action.up ) distance = +2 * delta; 55 if( action.down ) distance = -2 * delta; 56 if( distance ){ 57 var speed = new THREE.Vector3(0, 0, distance); 58 var matrix = new THREE.Matrix4().makeRotationY(model.rotation.y); 59 matrix.multiplyVector3(speed); 60 model.position.addSelf(speed); 61 } 62 }); 63 }); 64 65 tQuery.MinecraftCharKeyboard2.prototype.destroy = function(){ 66 opts.world.loop().unhook(this._$onLoop); 67 } 68 69 tQuery.MinecraftCharKeyboard2.prototype.opts = function(){ 70 return this._opts; 71 } 72 73