showing results for - "wasd controls javascript"
Sacha
05 Aug 2017
1function MyKeyUpHandler (MyEvent) { 
2   if (MyEvent.keyCode == 65 || MyEvent.keyCode == 68) {hero.velocity_x= 0}; // not left or right
3   if (MyEvent.keyCode == 87 || MyEvent.keyCode == 83) {hero.velocity_y= 0}; // not up or down
4   }
5
6
7function MyKeyDownHandler (MyEvent) { 
8   if (MyEvent.keyCode == 65) {hero.velocity_x=  -Quickness};  // left
9   if (MyEvent.keyCode == 87) {hero.velocity_y=  -Quickness};  // up
10   if (MyEvent.keyCode == 68) {hero.velocity_x=   Quickness};  // right
11   if (MyEvent.keyCode == 83) {hero.velocity_y=   Quickness};  // down
12   MyEvent.preventDefault();
13   }
14function MyTouchHandler (MyEvent) { 
15   var rect = myCanvas.getBoundingClientRect();           // where is our canvas
16   hero.velocity_y= 0; 
17   hero.velocity_x= 0;                                    // zero out velocity
18
19   for (var i=0; i < MyEvent.touches.length; i++) {
20       var x = MyEvent.touches[i].clientX - rect.left;    // get x & y coords
21       var y = MyEvent.touches[i].clientY - rect.top;     // relative to canvas
22
23       // Add velocity depending on which thirds we see touch
24
25       if (x > myCanvas.width * 0.66) hero.velocity_x= hero.velocity_x + Quickness;  
26       if (x < myCanvas.width * 0.33) hero.velocity_x= hero.velocity_x - Quickness;  
27       if (y > myCanvas.height * 0.66) hero.velocity_y= hero.velocity_y + Quickness; 
28       if (y < myCanvas.height * 0.33) hero.velocity_y= hero.velocity_y - Quickness; 
29       }
30
31   MyEvent.preventDefault();   
32   }