Showing posts with label Snippet. Show all posts
Showing posts with label Snippet. Show all posts

Sunday, 17 July 2011

Snippet List

I'll be writing a bunch of snippets for you guys to use as you please. I'm sure you will find a lot of use with them for making games, and probably other stuff too.

I'll keep this list updated when I think of more stuff to put in it. And I'm open to suggestions, if you have any, you can contact me via @SlashGame on twitter (By the way, I'm more likely to see a mention than a Private Message).



Draw Image with Rotation
Draw Text to Canvas
Play Sound (HTML5 Audio)
Mouse Input
Keyboard Input
AJAX

Snippet - AJAX

This is useful for many things with HTML5 game development. You could use it as a means to pass a user's score to a php script which adds it to a database.
Or you could do it the other way round, and make it get the highscores from the database, and the function would return the script's response, which could be used to then write the scores on the canvas, or wherever.


For Example:
ajaxCall("addScore.php?username=Slash&score=500");

That would have called the php script in addScore.php, and passed in the username and score parameters.
The php script could have simply been written to take those parameters with $_GET['username'] and $_GET['score'], and insert the values into a MySQL database.


This is just a snippet. I might later make a full tutorial on how to keep a scoreboard. But this function will allow you to call any php script with AJAX and use it's responseText if necessary.


The JavaScript Code:
function ajaxCall(scriptURL) {
  var xmlhttp;
  if(window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
       return xmlhttp.responseText;
     }
  }
  
  xmlhttp.open("GET", scriptURL, true);
  xmlhttp.send();
}


Example PHP Script:
// set up connection
$con = mysql_connect("localhost", "DBuser","DBpass") or die(mysql_error());
mysql_select_db("DBname", $con) or die(mysql_error());

// Get params from the url used
$username = mysql_real_escape_string($_GET['username']);
$score = mysql_real_escape_string($_GET['score']);

// insert the score into the scores table for the user
$query = "INSERT INTO scores (username, score) VALUES ('" . $username . "', '" . $score . "')";
mysql_query($query, $con) or die(mysql_error());


This example PHP script will work for the stuff I mentioned earlier, calling the JavaScript function with something like ajaxCall("addScore.php?username=Slash&score=500");

Note that this is an example to show what goes on with AJAX. However, in a professional situation, PDO would be used rather than MySQL, and jQuery would often be used in the JavaScript. Libraries are used a lot because they are already optimized code and you also have less code to write yourself.

Snippet - Keyboard Input for HTML5 Games

Examples of use:
If you wanted to check if the A key is pressed down:
if (isKeyPressed('a')==true) { /* do whatever */ }
If you wanted to check for the left arrow key being pressed:
isKeyPressed('left')
For escape key:
isKeyPressed('esc')



The Code:
window.addEventListener('keydown',keyPressDown,true);
window.addEventListener('keyup',keyPressUp,true);

function keyPressDown(evt){
 keys[evt.keyCode] = true;
}
function keyPressUp(evt){
 keys[evt.keyCode] = false;
}


function isKeyPressed(checkKey) {
 
 // alphabet
 if ((checkKey == 'a' || checkKey == 'A') && (65 in keys && keys[65])){
  return true;
 }
 else if ((checkKey == 'b' || checkKey == 'B') && (66 in keys && keys[66])){
  return true;
 }
 else if ((checkKey == 'c' || checkKey == 'C') && (67 in keys && keys[67])){
  return true;
 }
 else if ((checkKey == 'd' || checkKey == 'D') && (68 in keys && keys[68])){
  return true;
 }
 else if ((checkKey == 'e' || checkKey == 'E') && (69 in keys && keys[69])){
  return true;
 }
 else if ((checkKey == 'f' || checkKey == 'F') && (70 in keys && keys[70])){
  return true;
 }
 else if ((checkKey == 'g' || checkKey == 'G') && (71 in keys && keys[71])){
  return true;
 }
 else if ((checkKey == 'h' || checkKey == 'H') && (72 in keys && keys[72])){
  return true;
 }
 else if ((checkKey == 'i' || checkKey == 'I') && (73 in keys && keys[73])){
  return true;
 }
 else if ((checkKey == 'j' || checkKey == 'J') && (74 in keys && keys[74])){
  return true;
 }
 else if ((checkKey == 'k' || checkKey == 'K') && (75 in keys && keys[75])){
  return true;
 }
 else if ((checkKey == 'l' || checkKey == 'L') && (76 in keys && keys[76])){
  return true;
 }
 else if ((checkKey == 'm' || checkKey == 'M') && (77 in keys && keys[77])){
  return true;
 }
 else if ((checkKey == 'n' || checkKey == 'N') && (78 in keys && keys[78])){
  return true;
 }
 else if ((checkKey == 'o' || checkKey == 'O') && (79 in keys && keys[79])){
  return true;
 }
 else if ((checkKey == 'p' || checkKey == 'P') && (80 in keys && keys[80])){
  return true;
 }
 else if ((checkKey == 'q' || checkKey == 'Q') && (81 in keys && keys[81])){
  return true;
 }
 else if ((checkKey == 'r' || checkKey == 'R') && (82 in keys && keys[82])){
  return true;
 }
 else if ((checkKey == 's' || checkKey == 'S') && (83 in keys && keys[83])){
  return true;
 }
 else if ((checkKey == 't' || checkKey == 'T') && (84 in keys && keys[84])){
  return true;
 }
 else if ((checkKey == 'u' || checkKey == 'U') && (85 in keys && keys[85])){
  return true;
 }
 else if ((checkKey == 'v' || checkKey == 'V') && (86 in keys && keys[86])){
  return true;
 }
 else if ((checkKey == 'w' || checkKey == 'W') && (87 in keys && keys[87])){
  return true;
 }
 else if ((checkKey == 'x' || checkKey == 'X') && (88 in keys && keys[88])){
  return true;
 }
 else if ((checkKey == 'y' || checkKey == 'Y') && (89 in keys && keys[89])){
  return true;
 }
 else if ((checkKey == 'z' || checkKey == 'Z') && (90 in keys && keys[90])){
  return true;
 }
 
 
 //numbers
 else if ((checkKey == '0') && (48 in keys && keys[48])){
  return true;
 }
 else if ((checkKey == '1') && (49 in keys && keys[49])){
  return true;
 }
 else if ((checkKey == '2') && (50 in keys && keys[50])){
  return true;
 }
 else if ((checkKey == '3') && (51 in keys && keys[51])){
  return true;
 }
 else if ((checkKey == '4') && (52 in keys && keys[52])){
  return true;
 }
 else if ((checkKey == '5') && (53 in keys && keys[53])){
  return true;
 }
 else if ((checkKey == '6') && (54 in keys && keys[54])){
  return true;
 }
 else if ((checkKey == '7') && (55 in keys && keys[55])){
  return true;
 }
 else if ((checkKey == '8') && (56 in keys && keys[56])){
  return true;
 }
 else if ((checkKey == '9') && (57 in keys && keys[57])){
  return true;
 }
 
 
 // special keys
 else if ((checkKey == 'left' || checkKey == 'LEFT') && (37 in keys && keys[37])){
  return true;
 }
 else if ((checkKey == 'right' || checkKey == 'RIGHT') && (39 in keys && keys[39])){
  return true;
 }
 else if ((checkKey == 'up' || checkKey == 'UP') && (38 in keys && keys[38])){
  return true;
 }
 else if ((checkKey == 'down' || checkKey == 'DOWN') && (40 in keys && keys[40])){
  return true;
 }
 else if ((checkKey == 'esc' || checkKey == 'ESC' || checkKey == 'escape' || checkKey == 'ESCAPE' ) && (27 in keys && keys[27])){
  return true;
 }
 
}

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.

Snippet - Play Sound (HTML5 Audio)

Very simple set up and function:
var boingSound = new Audio("http://slashgame.net/boing.wav");
function playSound() {
 boingSound.currentTime = 0;
 boingSound.play();
}


Example usage: ---CLICK HERE---

Taken from HTML5 Audio Quick Tip

Snippet - Draw Text to HTML5 Canvas

This function draws text to the canvas with a specified position, color and font.
function drawCanvasText(txt, pX, pY, clr, fnt) {
 context2D.fillStyle = clr; // color
 context2D.font = fnt; // font
 context2D.fillText(txt, pX, pY); // text at position X, Y
}


Example Usage:
drawCanvasText("drawing text yas", 50, 50, "black", "bold 30px sans-serif");

Snippet - Draw Image with Rotation (HTML5 Games)

This is a function that draws an image with specified rotation.
(I first posted this function in the Rotate Image on Canvas tutorial.

function drawImg(img, pX, pY, oX, oY, w, h, rot) {
 context2D.save();
  context2D.translate(pX+oX, pY+oY);
  context2D.rotate(rot * Math.PI / 180);
  context2D.drawImage(img, 0, 0, w, h, -(oX), -(oY), w, h);
 context2D.restore();
}

Note:
img: the image object
pX: the x position of the image
pY: the y position of the image
oX: how far across the image that the origin is
oY: how far down the image that the origin is
w: width of the image
h: height of the image
rot: angle of rotation