Advertisement
Guest User

Untitled

a guest
Jun 27th, 2014
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. pc.script.create('dynamic_character_controller', function (context) {
  2.     var SPEED = 5;
  3.     var JUMP_IMPULSE = 400;
  4.    
  5.     var origin = pc.Vec3(0,0,0);
  6.     var groundCheckRay = pc.Vec3(0, -0.51, 0);
  7.     var rayEnd = pc.Vec3(0,0,0);
  8.    
  9.     var DynamicCharacterController = function (entity) {
  10.         this.entity = entity;
  11.        
  12.         this.speed = SPEED;
  13.         this.jumpImpulse = pc.Vec3(0, JUMP_IMPULSE, 0);
  14.            
  15.         this.onGround = true;
  16.     };
  17.  
  18.     DynamicCharacterController.prototype = {
  19.         initialize: function () {
  20.             // Prevent any rotation of the rigid body
  21.             this.entity.rigidbody.angularFactor = 0;
  22.         },
  23.        
  24.         update: function (dt) {
  25.             this._checkGround();    
  26.         },
  27.            
  28.         /**
  29.         * Move the character in the direction supplied
  30.         */
  31.         move: function (direction) {
  32.             if (this.onGround) {
  33.                 this.entity.rigidbody.activate();
  34.                 pc.Vec3.scale(direction, this.speed, direction);
  35.                 this.entity.rigidbody.linearVelocity = pc.Vec3(direction[0], direction[1], direction[2]);
  36.             }
  37.         },
  38.        
  39.         /**
  40.         * Make the character jump
  41.         */
  42.         jump: function () {
  43.             if (this.onGround) {
  44.                 this.self.rigidbody.activate();
  45.                 this.self.rigidbody.applyImpulse(this.jumpImpulse, origin);
  46.                 this.onGround = false;                
  47.             }
  48.         },
  49.        
  50.         /**
  51.         * Check to see if the character is standing on something
  52.         */
  53.         _checkGround: function () {
  54.             var self = this;
  55.             var pos = this.entity.getPosition();
  56.             pc.Vec3.add(pos, groundCheckRay, rayEnd);
  57.             self.onGround = false;
  58.  
  59.             // Fire a ray straight down to just below the bottom of the rigid body,
  60.             // if it hits something then the character is standing on something.
  61.             context.systems.rigidbody.raycastFirst(pos, rayEnd, function (result) {
  62.                 self.onGround = true;
  63.             });
  64.         }
  65.     };
  66.  
  67.    return DynamicCharacterController;
  68. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement