Introduction to CraftyJS : Detecting Mouse and Keyboard Events

  • Mouse Events

// When the DOM has loaded
$(document).ready(function() {

// Height and Width
 var WIDTH = 500, HEIGHT = 320;

// Initialize Crafty
 Crafty.init(WIDTH, HEIGHT);

// Background
 Crafty.background("black");

// Create a player entity
 var player = Crafty.e();

// Add some components to the entity
 player.addComponent("2D, DOM");

player.attr({
 x : 220,
 y : 120,
 w : 50,
 h : 50
 });

player.addComponent("Color").color("red");

//add mouse component for mouse events
 player.addComponent("Mouse");

 player.bind('Click', function(e) {
 alert("Clicked");
 });
});

  • KeyBoard Events

// When the DOM has loaded
$(document).ready(function() {

// Height and Width
var WIDTH = 500, HEIGHT = 320;

// Initialize Crafty
Crafty.init(WIDTH, HEIGHT);

// Background
Crafty.background("black");

// Create a player entity
var player = Crafty.e();

// Add some components to the entity
player.addComponent("2D, DOM");

player.attr({ x:20, y: 20, w:50, h:50 });

player.addComponent("Color").color("red");

player.bind('KeyDown', function(e) {
if(e.key == Crafty.keys['LEFT_ARROW']) {
this.x=this.x-5;
} else if (e.key == Crafty.keys['RIGHT_ARROW']) {
this.x=this.x+5;
} else if (e.key == Crafty.keys['UP_ARROW']) {
this.y=this.y-5;
} else if (e.key == Crafty.keys['DOWN_ARROW']) {
this.y=this.y+5;
}
});

});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s