Saturday, 16 July 2011

Snippet - Mouse Input for HTML5 Games

The following code can all be copy-pasted to your javascript and used how you wish.
Keep in mind the clicked() function is empty, because you chose what goes in there if you need to use it. The rest simply set variables that can be used later in the code. (i.e. mouseX, mouseY and ismousedown)

var mouseX = 0;
var mouseY = 0;
window.addEventListener('mousemove', mouseMoved, true);
function mouseMoved(e) {
 mouseX = e.pageX;
 mouseY = e.pageY;
// ^put that in your code and you will be able
// to use mouseX and mouseY variables anywhere in that code.

window.addEventListener('click', clicked, true);
function clicked(e) {
 // you can put whatever you want in here
 // for example, you could use the mouseX and mouseY variables
 // to place a bullet-hole image where the mouse was when clicked

var ismousedown = 0;
window.onmousedown = function(e) {
 ismousedown = 1;
window.onmouseup = function(e) {
 ismousedown = 0;
// ^with this code, you can now check the ismousedown variables
// at any time to check if the mouse is being clicked
// useful for mouse dragging or for holding the "shoot button", etc.