Path: blob/main/public/games/files/algaes-escapade/js/lib/lever.js
1038 views
/**1* Represents a lever. Levers can be pulled and turned on or off, but must be2* held down or they will revert to their off state3*4* @author David North5*/6function lever()7{8lever.prototype.constructor.call(this);910//Fulfil the requirements of the gamejs.sprite.Sprite object11this.image = gamejs.image.load('img/switch.png');12this.image.crop( new gamejs.Rect( [0,0], [83,43] ));1314var _size = this.image.getSize();1516/**17* @var boolean Whether or the lever is being held down18*/19var _heldDown = false;2021this.rect = new gamejs.Rect([0, 0], [_size[0], _size[1]]);2223/**24* Overrides the setState method of the parent so that the object changes25* depending on whether it is on or off26*27* @param boolean state The state to apply28*29* @return lever30*/31this.setState = function( state ){32if ( state != this.getState() )33{34if ( state )35{36this.image.crop( new gamejs.Rect( [83,0], [83,43] ));37}38else39{40this.image.crop( new gamejs.Rect( [0,0], [83,43] ));41}42}4344//Update the state using the parent setState method45lever.prototype.setState.call(this, state);46}4748/**49* Updates the object, ready for the next draw request50*51* @param msDuration52*53* @return lever54*/55this.update = function( msDuration ){56//If the lever isn't held down then turn it off57if ( !_heldDown )58{59this.setState(false);60}6162//the default state is to be not held down, unless otherwise told63_heldDown = false;6465return this;66}6768/**69* Handles the collision between a playable and this object70*71* @param playable playable The playable that collision has happened on72*73* @return lever74*/75this.handleCollision = function( playable ){7677if ( _hasCollided(this, playable ) )78{79//If the player is colliding with this lever then it is held down80_heldDown = true;81}8283return this;84}8586/**87* Handles player input. If the player activates the switch then actions88* may need to be taken89*90* @param world world The world this event came from91* @param gamejs.Event event The event that fired92*/93this.handleInput = function(world, event){94var playable = world.getPlayer().getCurrentPlayable();9596//Only check the event if a key has been pushed and the player is97//colliding with the lever98if ( event.type === gamejs.event.KEY_DOWN99&& _hasCollided(this, playable) )100{101//If the key was 'enter' or 'e' then set the new state of the lever102switch( event.key )103{104case gamejs.event.K_e:105case gamejs.event.K_ENTER:106this.setState( !this.getState() );107break;108}109}110}111112var _hasCollided = function ( self, playable )113{114var _collideRect = new gamejs.Rect(115[self.rect.x + 34, self.rect.y],116[32 , _size[1]]117);118119return _collideRect.collideRect(playable.rect);120}121}122123//Set the parent of the lever to io124include_once(['lib/io.js']);125lever.prototype = new io();126127128