SlideShare a Scribd company logo
1 of 19
Download to read offline
Hello I’m Jafar
 Multiplayer Worlds
           with
     Node.js + HTML




http://jaf.ar.com
Inspired By

      RED INTERACTIVE
        http://FF0000




2009 - I Love Flash
2010 - Steve Jobs Hates Flash
2011 - Flash dies slow death... :(
My Website is....




     Not perfect....

Probably really hackable...

   Still using globals....

 Chat room needs filters...

 Server not authoritave
OH NO BUGS IN CHROME!


Works well in Chrome 19 !
        Download Chrome Canary


Worked well in Chrome 16

 Chrome updates to 17...
   ...bugs come back
                   (image flicker)



 Might be a cache issue....
 Might be a Mac thing...
 Maybe Wifi on Mac thing
http://www.eclipse.org/forums/index.php/mv/tree/262108/#page_top
MICROSOFT SAYS
 NO WEBSOCKETS

So Screw IE9 or Lower
      and Opera and Safari



 Although Socket.io does
work on browsers without
      web sockets
           (too choppy)




   Microsoft Changes Their Mind
   IE10 pretty good....
STACK


Node.js - server
Socket.IO - cross browser sockets
Now.js - namespace, easy chat rooms

Express - static files, pages
jQuery - front end stuff
World.js
//ANIMATION LOOP
window.requestAnimFrame = (function(){
   return window.requestAnimationFrame ||
   window.webkitRequestAnimationFrame ||
   window.mozRequestAnimationFrame ||
   window.msRequestAnimationFrame
})();




         //MAIN LOOP
         (function animloop(){

               moveCamera();
               gravity();
               floor();

               myPlayer();
               movePlayers();
               controlPlayer();

               moveLasers();
               otherLasers();

               requestAnimFrame(animloop);

         })();
JUST USE HTML DIV’s
         Canvas too slow for a large map
  Because when you draw on canvas you must also clear
              each move and each pixel
                3000 x 3000 = 9 Million px/sec
3000px




 3000px                       1920 x 1024

 “Tip: DOM is usually always faster than canvas....”
           http://craftyjs.com/demos/tutorial/tutorial.html
Where is My Player?
           in relation to the DOM Window


var PosX = $('#myPlayer').offset().left - $(window).scrollLeft();


 #myPlayer                             .player                .player

     .player



                                       .player                .player




 if( PosX < 50 || PosX > (winW - 50) )            //within 50px of window



 window.scrollBy(x,y);     //scroll the window to keep player in view
var players = {};

     id, x, y, direction, moving, floor, skin


                                   CLIENT
 //KEY DOWN
 function kdRight(){
      now.pullPlayers(now.core.clientId,player.x, player.y, 0,1,floor_y,skin_num);
 }


                                   SERVER
//PULL PLAYERS
everyone.now.pullPlayers = function(id,x,y,dir,mov,flo,skin){

       actors[id] = {x:x, y:y, dir:dir, mov:mov,flo:flo,skin:skin};

       var playerUpdate = {};
       playerUpdate = {id:id,x:x,y:y,dir:dir,mov:mov,flo:flo,skin:skin};
       everyone.now.showPlayers(playerUpdate);

};



                                      CLIENT
//SHOW PLAYERS
now.showPlayers = function(plyr) {
     players[plyr.id] = {x:plyr.x, y:plyr.y, dir:plyr.dir, mov:plyr.mov,flo:plyr.flo,skin:plyr.skin};
}



            >>>> LOOP THE PLAYERS OBJECT
Animation Loop
//MOVE PLAYERS
function movePlayers(){

      //FOR LOOP
     for(var i in players) {

           //REMOVE
           $(".player[rel='" + i + "']").remove();

           //ADD
           $('#Players').append('<div class="player" rel="' + i + '"></div>');


           >>>>IF MOVING (next page)
           >>>>ELSE STANDING STILL (next page)


     }


}
//MOVING
if(players[i].mov == 1) {

        //LEFT
        if(players[i].dir == 1) {

            players[i].x--;
            $(".player[rel='"+ i +"']").css('left', players[i].x );
            $(".player[rel='"+ i +"']").css('top', players[i].y );
            $(".player[rel='"+ i +"']").css('background-image',img_walk_l);

        //RIGHT
        } else if(players[i].dir == 0){

            players[i].x ++;
            $(".player[rel='"+ i +"']").css('left', players[i].x );
            $(".player[rel='"+ i +"']").css('top', players[i].y );
            $(".player[rel='"+ i +"']").css('background-image',img_walk_r);

        } else {

            $(".player[rel='"+ i +"']").css('left', players[i].x );
            $(".player[rel='"+ i +"']").css('top', players[i].y );
            $(".player[rel='"+ i +"']").css('background-image',img_front);
        }


 //STANDING STILL
} else {

        //LEFT
        if(players[i].dir == 1) {
           $(".player[rel='"+ i +"']").css('background-image',img_l);
           $(".player[rel='"+ i +"']").css('left', players[i].x );
           $(".player[rel='"+ i +"']").css('top', players[i].y );
        //RIGHT
        } else if (players[i].dir == 0){
           $(".player[rel='"+ i +"']").css('background-image',img_r);
           $(".player[rel='"+ i +"']").css('left', players[i].x );
           $(".player[rel='"+ i +"']").css('top', players[i].y );
        //BACK
        } else if (players[i].dir == 'b'){
           $(".player[rel='"+ i +"']").css('background-image',img_back);
           $(".player[rel='"+ i +"']").css('left', players[i].x );
           $(".player[rel='"+ i +"']").css('top', players[i].y );
        //FRONT
        } else {
           $(".player[rel='"+ i +"']").css('background-image',img_front);
           $(".player[rel='"+ i +"']").css('left', players[i].x );
           $(".player[rel='"+ i +"']").css('top', players[i].y );
        }

//END MOV
}
Wait What About My Player
                  //GLOBALS
                  --movement
                  --leftKey
                  --rightKey


 //MY PLAYER
 function myPlayer() {

     if ( movement && leftKey ) {

           player.x --;
           $('#player').css('left',player.x );

     } else if ( movement && rightKey ) {

            player.x ++;
            $('#player').css('left',player.x );

     } else {

            $('#player').css('left',player.x );

      }

 //END FUNC
 }
GRAVITY LOOP
                        We use the global object “players{}”

//GRAVITY
function gravity() {

    //MY PLAYER
     if ( player.y !== floor_y ) {

             player.y ++;
             player.y ++;
             $('#player').css('top',player.y );
     }

    //FOR LOOP
    for (var i in players) {

         //IN THE AIR
         if( i === now.core.clientId && players[i].y !== floor_y ) {

                players[i].y++;
                players[i].y++;
                $(".player[rel='"+ i +"']").css('top', players[i].y );

         } else if ( i !== now.core.clientId && players[i].y !== players[i].flo) {

                players[i].y++;
                players[i].y++;
                $(".player[rel='"+ i +"']").css('top', players[i].y );

         } else {
                    //do nothing
         }

    }

}
FLOOR LOOP
                          changing players floor position

     //FLOOR
     function floor(){


            //FLOOR 1
           if(player.y == floor1 && player.x <= 810 && player.x >= 100){
                 floor_y = floor1;
                 player.y = floor1;
           }

           //FALLING
           if ( player.y == floor1 - 2 && player.x <= 810 && player.x >= 100) {
                  floor_y = floor1;
                  now.pullPlayers();
           }

           //JUMPING
           if ( player.y == floor1 + 2) {
                  now.pullPlayers();
           }


     //END FUNC
     }




                                    **PULL PLAYERS**
now.pullPlayers(now.core.clientId,player.x, player.y, direction, movement, floor_y,skin_num)
LASERS LOOP                                                           VARIABLES
                                                                       var lasers = [];
                                                                       var other_lasers = [];
                                                                       var laser_v = 27;

                                   CLIENT

 $(window).keyup(function(e) {

 case 191:
    if(!$(‘.placeHolder’).is(“:focus”)) {
       now.fireLasers(now.core.clientId,player.x + 12, player.y + 12, direction);
       lasers.push([player.x + 12, player.y + 12, direction]);
       e.preventDefault();
    }
    break;
 }

                                   SERVER
 //FIRE LASERS
 everyone.now.fireLasers = function(id,x,y,dir){

       var laserUpdate = {};
       laserUpdate = {id:id,x:x,y:y,dir:dir};
       everyone.now.showLasers(laserUpdate);

 };
                                   CLIENT

//SHOW LASERS
now.showLasers = function(laz) {
       if(laz.id != now.core.clientId) {
            other_lasers.push( [laz.x, laz.y, laz.dir] );
     }
}


       >>>> MOVE AND DRAW LASERS
Function to Draw Our Lasers
  //LASERS
  function drawLasers (x, y, dir) {

       if( dir == 0 || dir == 1) {
             game.clearRect(x,y,-65,2);
            game.clearRect(x, y,65,2);
            game.fillStyle = '#f00';
            game.fillRect(x, y,10,1);

           } else {

               game.clearRect(x,y,-2,65);
               game.clearRect(x, y,2,65);
               game.fillStyle = '#f00';
               game.fillRect(x, y,1,10);

       }

  }
MOVE LASERS

function moveLasers() {

     for(var i = 0; i < lasers.length; i++) {

         //IF WITHIN BOUNDS
         if(lasers[i][0] < player.x + w && lasers[i][0] > player.x - w && lasers[i][1] > 1500 ) {

            if(lasers[i][2] == 1) {
              lasers[i][0] -= laser_v;
            } else if(lasers[i][2] == 0){
              lasers[i][0] += laser_v;
            } else {

                lasers[i][1] -= laser_v;
            }

            drawLasers(lasers[i][0], lasers[i][1],lasers[i][2]);

         } else if(lasers[i][0] > player.x + w + 1 || lasers[i][0] < player.x - w +1){

            lasers.splice(i,1);

         } else if(lasers[i][1] < 0 ){

            lasers.splice(i,1);

         } else {
            //do nothing
         }


     }

 }
OTHER PLAYERS LASERS

function otherLasers() {

    for(var i = 0; i < other_lasers.length; i++) {

        if(other_lasers[i][0] < player.x + w && other_lasers[i][0] > player.x - w ) {

            if(other_lasers[i][2] == 1) {
              other_lasers[i][0] -= laser_v;
            } else if(other_lasers[i][2] == 0){
              other_lasers[i][0] += laser_v;
            } else {
              other_lasers[i][1] -= laser_v;
            }

            drawLasers(other_lasers[i][0], other_lasers[i][1],other_lasers[i][2]);


        } else {
            other_lasers.splice(i,1);

        }

    }

}

More Related Content

What's hot

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196Mahmoud Samir Fayed
 
Raspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFXRaspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFXStephen Chin
 
The Ring programming language version 1.2 book - Part 38 of 84
The Ring programming language version 1.2 book - Part 38 of 84The Ring programming language version 1.2 book - Part 38 of 84
The Ring programming language version 1.2 book - Part 38 of 84Mahmoud Samir Fayed
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Bongwon Lee
 
enchant js workshop on Calpoly
enchant js workshop  on Calpolyenchant js workshop  on Calpoly
enchant js workshop on CalpolyRyo Shimizu
 
The Ring programming language version 1.5 book - Part 9 of 31
The Ring programming language version 1.5 book - Part 9 of 31The Ring programming language version 1.5 book - Part 9 of 31
The Ring programming language version 1.5 book - Part 9 of 31Mahmoud Samir Fayed
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word documentrudrapratap61
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new featuresGephenSG
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내Jung Kim
 
The Ring programming language version 1.5.4 book - Part 46 of 185
The Ring programming language version 1.5.4 book - Part 46 of 185The Ring programming language version 1.5.4 book - Part 46 of 185
The Ring programming language version 1.5.4 book - Part 46 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 51 of 185
The Ring programming language version 1.5.4 book - Part 51 of 185The Ring programming language version 1.5.4 book - Part 51 of 185
The Ring programming language version 1.5.4 book - Part 51 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 53 of 189
The Ring programming language version 1.6 book - Part 53 of 189The Ring programming language version 1.6 book - Part 53 of 189
The Ring programming language version 1.6 book - Part 53 of 189Mahmoud Samir Fayed
 

What's hot (20)

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196The Ring programming language version 1.7 book - Part 57 of 196
The Ring programming language version 1.7 book - Part 57 of 196
 
Raspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFXRaspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFX
 
The Ring programming language version 1.2 book - Part 38 of 84
The Ring programming language version 1.2 book - Part 38 of 84The Ring programming language version 1.2 book - Part 38 of 84
The Ring programming language version 1.2 book - Part 38 of 84
 
Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9Simulator customizing & testing for Xcode 9
Simulator customizing & testing for Xcode 9
 
enchant js workshop on Calpoly
enchant js workshop  on Calpolyenchant js workshop  on Calpoly
enchant js workshop on Calpoly
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
The Ring programming language version 1.5 book - Part 9 of 31
The Ring programming language version 1.5 book - Part 9 of 31The Ring programming language version 1.5 book - Part 9 of 31
The Ring programming language version 1.5 book - Part 9 of 31
 
The jQuery Divide
The jQuery DivideThe jQuery Divide
The jQuery Divide
 
jQuery Loves You
jQuery Loves YoujQuery Loves You
jQuery Loves You
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내스위프트를 여행하는 히치하이커를 위한 스타일 안내
스위프트를 여행하는 히치하이커를 위한 스타일 안내
 
Prototype UI
Prototype UIPrototype UI
Prototype UI
 
The Ring programming language version 1.5.4 book - Part 46 of 185
The Ring programming language version 1.5.4 book - Part 46 of 185The Ring programming language version 1.5.4 book - Part 46 of 185
The Ring programming language version 1.5.4 book - Part 46 of 185
 
The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181
 
The Ring programming language version 1.5.4 book - Part 51 of 185
The Ring programming language version 1.5.4 book - Part 51 of 185The Ring programming language version 1.5.4 book - Part 51 of 185
The Ring programming language version 1.5.4 book - Part 51 of 185
 
The Ring programming language version 1.6 book - Part 53 of 189
The Ring programming language version 1.6 book - Part 53 of 189The Ring programming language version 1.6 book - Part 53 of 189
The Ring programming language version 1.6 book - Part 53 of 189
 
Ssaw08 0624
Ssaw08 0624Ssaw08 0624
Ssaw08 0624
 

Viewers also liked

How to Make Your Lobby Relaxing to The Guest
How to Make Your Lobby Relaxing to The Guest How to Make Your Lobby Relaxing to The Guest
How to Make Your Lobby Relaxing to The Guest Ashley Lori White
 
Presentatie Projectgroep Diemerbos | 14 oktober 2014
Presentatie Projectgroep Diemerbos | 14 oktober 2014Presentatie Projectgroep Diemerbos | 14 oktober 2014
Presentatie Projectgroep Diemerbos | 14 oktober 2014Diemerbos
 
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...Data Beers
 
Next Generation Economic Development Marketing Is Already Here
Next Generation Economic Development Marketing Is Already HereNext Generation Economic Development Marketing Is Already Here
Next Generation Economic Development Marketing Is Already HereGIS Planning
 
Color Study Final Assignment Part 3
Color Study Final Assignment Part 3Color Study Final Assignment Part 3
Color Study Final Assignment Part 3VivyCool
 
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve Shaw
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve ShawLeeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve Shaw
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve ShawBranded3
 
Designing for the User Experience Final Concept Presentation
Designing for the User Experience Final Concept PresentationDesigning for the User Experience Final Concept Presentation
Designing for the User Experience Final Concept PresentationPaul van Beek
 
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...Branded3
 
ShareThis Midterm Elections_2014
ShareThis Midterm Elections_2014ShareThis Midterm Elections_2014
ShareThis Midterm Elections_2014ShareThis
 
On Microbrews and Translation
On Microbrews and TranslationOn Microbrews and Translation
On Microbrews and TranslationTerena Bell
 
Alternative Rock Week 3
Alternative Rock Week 3Alternative Rock Week 3
Alternative Rock Week 3Keith Hennigan
 
Reglamento institucional upc
Reglamento institucional upcReglamento institucional upc
Reglamento institucional upcDaviid07
 
Know Your Audience: Low-Budget Research Methods
Know Your Audience: Low-Budget Research MethodsKnow Your Audience: Low-Budget Research Methods
Know Your Audience: Low-Budget Research MethodsMark Wood
 
A Framework for Action
A Framework for ActionA Framework for Action
A Framework for ActionJordan Teague
 
A normal day. salva, diego y fran
A normal day. salva, diego y franA normal day. salva, diego y fran
A normal day. salva, diego y franfranvato
 
Redefining Brand Engagement in an LBS / AR Enabled World
Redefining Brand Engagement in an LBS / AR Enabled WorldRedefining Brand Engagement in an LBS / AR Enabled World
Redefining Brand Engagement in an LBS / AR Enabled WorldBrian Selzer
 
WEB: State of the art
WEB: State of the artWEB: State of the art
WEB: State of the artJon Eguiluz
 

Viewers also liked (20)

How to Make Your Lobby Relaxing to The Guest
How to Make Your Lobby Relaxing to The Guest How to Make Your Lobby Relaxing to The Guest
How to Make Your Lobby Relaxing to The Guest
 
Presentatie Projectgroep Diemerbos | 14 oktober 2014
Presentatie Projectgroep Diemerbos | 14 oktober 2014Presentatie Projectgroep Diemerbos | 14 oktober 2014
Presentatie Projectgroep Diemerbos | 14 oktober 2014
 
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...
[Databeers] 17/06/2014 - Ignacio Bustillo: “Data Master Chef. Cocinando datos...
 
Next Generation Economic Development Marketing Is Already Here
Next Generation Economic Development Marketing Is Already HereNext Generation Economic Development Marketing Is Already Here
Next Generation Economic Development Marketing Is Already Here
 
Color Study Final Assignment Part 3
Color Study Final Assignment Part 3Color Study Final Assignment Part 3
Color Study Final Assignment Part 3
 
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve Shaw
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve ShawLeeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve Shaw
Leeds #B3Seminar: Using Visitor Intent and Sitecore Personalisation - Steve Shaw
 
Designing for the User Experience Final Concept Presentation
Designing for the User Experience Final Concept PresentationDesigning for the User Experience Final Concept Presentation
Designing for the User Experience Final Concept Presentation
 
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...
London #B3Seminar: How many SEOs does it take to sell a lightbulb? - Stephen ...
 
ShareThis Midterm Elections_2014
ShareThis Midterm Elections_2014ShareThis Midterm Elections_2014
ShareThis Midterm Elections_2014
 
On Microbrews and Translation
On Microbrews and TranslationOn Microbrews and Translation
On Microbrews and Translation
 
by Mazen Saeed
by Mazen Saeedby Mazen Saeed
by Mazen Saeed
 
Alternative Rock Week 3
Alternative Rock Week 3Alternative Rock Week 3
Alternative Rock Week 3
 
Reglamento institucional upc
Reglamento institucional upcReglamento institucional upc
Reglamento institucional upc
 
Know Your Audience: Low-Budget Research Methods
Know Your Audience: Low-Budget Research MethodsKnow Your Audience: Low-Budget Research Methods
Know Your Audience: Low-Budget Research Methods
 
SmartChurch Premium Detailed Presentation
SmartChurch Premium   Detailed PresentationSmartChurch Premium   Detailed Presentation
SmartChurch Premium Detailed Presentation
 
A Framework for Action
A Framework for ActionA Framework for Action
A Framework for Action
 
A normal day. salva, diego y fran
A normal day. salva, diego y franA normal day. salva, diego y fran
A normal day. salva, diego y fran
 
Redefining Brand Engagement in an LBS / AR Enabled World
Redefining Brand Engagement in an LBS / AR Enabled WorldRedefining Brand Engagement in an LBS / AR Enabled World
Redefining Brand Engagement in an LBS / AR Enabled World
 
WEB: State of the art
WEB: State of the artWEB: State of the art
WEB: State of the art
 
Biologi virus
Biologi virusBiologi virus
Biologi virus
 

Similar to Node.js multiplayer HTML5 game

Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017名辰 洪
 
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021Andrzej Jóźwiak
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdffazilfootsteps
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Doris Chen
 
Drush. Secrets come out.
Drush. Secrets come out.Drush. Secrets come out.
Drush. Secrets come out.Alex S
 
Report: Avalanche 'very likely' to host outdoor game at Coors Field
Report: Avalanche 'very likely' to host outdoor game at Coors FieldReport: Avalanche 'very likely' to host outdoor game at Coors Field
Report: Avalanche 'very likely' to host outdoor game at Coors Fieldfabulouspsychop39
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
groovy databases
groovy databasesgroovy databases
groovy databasesPaul King
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScriptSam Cartwright
 
Really Fast HTML5 Game Development with CreateJS
Really Fast HTML5 Game Development with CreateJSReally Fast HTML5 Game Development with CreateJS
Really Fast HTML5 Game Development with CreateJSDave Kelleher
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with SpockAlexander Tarlinder
 
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docx
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docxcirc.db.dbcircleserver(1).py#!usrlocalbinpython3im.docx
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docxchristinemaritza
 

Similar to Node.js multiplayer HTML5 game (20)

Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021Capability Driven Design - Andrzej Jóźwiak  - TomTom Dev Day 2021
Capability Driven Design - Andrzej Jóźwiak - TomTom Dev Day 2021
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdfIfgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
Ifgqueue.h#ifndef LFGQUEUE_H #define LFGQUEUE_H#include pl.pdf
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
Drush. Secrets come out.
Drush. Secrets come out.Drush. Secrets come out.
Drush. Secrets come out.
 
Report: Avalanche 'very likely' to host outdoor game at Coors Field
Report: Avalanche 'very likely' to host outdoor game at Coors FieldReport: Avalanche 'very likely' to host outdoor game at Coors Field
Report: Avalanche 'very likely' to host outdoor game at Coors Field
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
Really Fast HTML5 Game Development with CreateJS
Really Fast HTML5 Game Development with CreateJSReally Fast HTML5 Game Development with CreateJS
Really Fast HTML5 Game Development with CreateJS
 
Javascript
JavascriptJavascript
Javascript
 
Save game function
Save game functionSave game function
Save game function
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with Spock
 
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docx
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docxcirc.db.dbcircleserver(1).py#!usrlocalbinpython3im.docx
circ.db.dbcircleserver(1).py#!usrlocalbinpython3im.docx
 

Recently uploaded

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Recently uploaded (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Node.js multiplayer HTML5 game

  • 1. Hello I’m Jafar Multiplayer Worlds with Node.js + HTML http://jaf.ar.com
  • 2. Inspired By RED INTERACTIVE http://FF0000 2009 - I Love Flash 2010 - Steve Jobs Hates Flash 2011 - Flash dies slow death... :(
  • 3. My Website is.... Not perfect.... Probably really hackable... Still using globals.... Chat room needs filters... Server not authoritave
  • 4. OH NO BUGS IN CHROME! Works well in Chrome 19 ! Download Chrome Canary Worked well in Chrome 16 Chrome updates to 17... ...bugs come back (image flicker) Might be a cache issue.... Might be a Mac thing... Maybe Wifi on Mac thing http://www.eclipse.org/forums/index.php/mv/tree/262108/#page_top
  • 5. MICROSOFT SAYS NO WEBSOCKETS So Screw IE9 or Lower and Opera and Safari Although Socket.io does work on browsers without web sockets (too choppy) Microsoft Changes Their Mind IE10 pretty good....
  • 6. STACK Node.js - server Socket.IO - cross browser sockets Now.js - namespace, easy chat rooms Express - static files, pages jQuery - front end stuff
  • 7. World.js //ANIMATION LOOP window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame })(); //MAIN LOOP (function animloop(){ moveCamera(); gravity(); floor(); myPlayer(); movePlayers(); controlPlayer(); moveLasers(); otherLasers(); requestAnimFrame(animloop); })();
  • 8. JUST USE HTML DIV’s Canvas too slow for a large map Because when you draw on canvas you must also clear each move and each pixel 3000 x 3000 = 9 Million px/sec 3000px 3000px 1920 x 1024 “Tip: DOM is usually always faster than canvas....” http://craftyjs.com/demos/tutorial/tutorial.html
  • 9. Where is My Player? in relation to the DOM Window var PosX = $('#myPlayer').offset().left - $(window).scrollLeft(); #myPlayer .player .player .player .player .player if( PosX < 50 || PosX > (winW - 50) ) //within 50px of window window.scrollBy(x,y); //scroll the window to keep player in view
  • 10. var players = {}; id, x, y, direction, moving, floor, skin CLIENT //KEY DOWN function kdRight(){ now.pullPlayers(now.core.clientId,player.x, player.y, 0,1,floor_y,skin_num); } SERVER //PULL PLAYERS everyone.now.pullPlayers = function(id,x,y,dir,mov,flo,skin){ actors[id] = {x:x, y:y, dir:dir, mov:mov,flo:flo,skin:skin}; var playerUpdate = {}; playerUpdate = {id:id,x:x,y:y,dir:dir,mov:mov,flo:flo,skin:skin}; everyone.now.showPlayers(playerUpdate); }; CLIENT //SHOW PLAYERS now.showPlayers = function(plyr) { players[plyr.id] = {x:plyr.x, y:plyr.y, dir:plyr.dir, mov:plyr.mov,flo:plyr.flo,skin:plyr.skin}; } >>>> LOOP THE PLAYERS OBJECT
  • 11. Animation Loop //MOVE PLAYERS function movePlayers(){ //FOR LOOP for(var i in players) { //REMOVE $(".player[rel='" + i + "']").remove(); //ADD $('#Players').append('<div class="player" rel="' + i + '"></div>'); >>>>IF MOVING (next page) >>>>ELSE STANDING STILL (next page) } }
  • 12. //MOVING if(players[i].mov == 1) { //LEFT if(players[i].dir == 1) { players[i].x--; $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); $(".player[rel='"+ i +"']").css('background-image',img_walk_l); //RIGHT } else if(players[i].dir == 0){ players[i].x ++; $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); $(".player[rel='"+ i +"']").css('background-image',img_walk_r); } else { $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); $(".player[rel='"+ i +"']").css('background-image',img_front); } //STANDING STILL } else { //LEFT if(players[i].dir == 1) { $(".player[rel='"+ i +"']").css('background-image',img_l); $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); //RIGHT } else if (players[i].dir == 0){ $(".player[rel='"+ i +"']").css('background-image',img_r); $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); //BACK } else if (players[i].dir == 'b'){ $(".player[rel='"+ i +"']").css('background-image',img_back); $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); //FRONT } else { $(".player[rel='"+ i +"']").css('background-image',img_front); $(".player[rel='"+ i +"']").css('left', players[i].x ); $(".player[rel='"+ i +"']").css('top', players[i].y ); } //END MOV }
  • 13. Wait What About My Player //GLOBALS --movement --leftKey --rightKey //MY PLAYER function myPlayer() { if ( movement && leftKey ) { player.x --; $('#player').css('left',player.x ); } else if ( movement && rightKey ) { player.x ++; $('#player').css('left',player.x ); } else { $('#player').css('left',player.x ); } //END FUNC }
  • 14. GRAVITY LOOP We use the global object “players{}” //GRAVITY function gravity() { //MY PLAYER if ( player.y !== floor_y ) { player.y ++; player.y ++; $('#player').css('top',player.y ); } //FOR LOOP for (var i in players) { //IN THE AIR if( i === now.core.clientId && players[i].y !== floor_y ) { players[i].y++; players[i].y++; $(".player[rel='"+ i +"']").css('top', players[i].y ); } else if ( i !== now.core.clientId && players[i].y !== players[i].flo) { players[i].y++; players[i].y++; $(".player[rel='"+ i +"']").css('top', players[i].y ); } else { //do nothing } } }
  • 15. FLOOR LOOP changing players floor position //FLOOR function floor(){ //FLOOR 1 if(player.y == floor1 && player.x <= 810 && player.x >= 100){ floor_y = floor1; player.y = floor1; } //FALLING if ( player.y == floor1 - 2 && player.x <= 810 && player.x >= 100) { floor_y = floor1; now.pullPlayers(); } //JUMPING if ( player.y == floor1 + 2) { now.pullPlayers(); } //END FUNC } **PULL PLAYERS** now.pullPlayers(now.core.clientId,player.x, player.y, direction, movement, floor_y,skin_num)
  • 16. LASERS LOOP VARIABLES var lasers = []; var other_lasers = []; var laser_v = 27; CLIENT $(window).keyup(function(e) { case 191: if(!$(‘.placeHolder’).is(“:focus”)) { now.fireLasers(now.core.clientId,player.x + 12, player.y + 12, direction); lasers.push([player.x + 12, player.y + 12, direction]); e.preventDefault(); } break; } SERVER //FIRE LASERS everyone.now.fireLasers = function(id,x,y,dir){ var laserUpdate = {}; laserUpdate = {id:id,x:x,y:y,dir:dir}; everyone.now.showLasers(laserUpdate); }; CLIENT //SHOW LASERS now.showLasers = function(laz) { if(laz.id != now.core.clientId) { other_lasers.push( [laz.x, laz.y, laz.dir] ); } } >>>> MOVE AND DRAW LASERS
  • 17. Function to Draw Our Lasers //LASERS function drawLasers (x, y, dir) { if( dir == 0 || dir == 1) { game.clearRect(x,y,-65,2); game.clearRect(x, y,65,2); game.fillStyle = '#f00'; game.fillRect(x, y,10,1); } else { game.clearRect(x,y,-2,65); game.clearRect(x, y,2,65); game.fillStyle = '#f00'; game.fillRect(x, y,1,10); } }
  • 18. MOVE LASERS function moveLasers() { for(var i = 0; i < lasers.length; i++) { //IF WITHIN BOUNDS if(lasers[i][0] < player.x + w && lasers[i][0] > player.x - w && lasers[i][1] > 1500 ) { if(lasers[i][2] == 1) { lasers[i][0] -= laser_v; } else if(lasers[i][2] == 0){ lasers[i][0] += laser_v; } else { lasers[i][1] -= laser_v; } drawLasers(lasers[i][0], lasers[i][1],lasers[i][2]); } else if(lasers[i][0] > player.x + w + 1 || lasers[i][0] < player.x - w +1){ lasers.splice(i,1); } else if(lasers[i][1] < 0 ){ lasers.splice(i,1); } else { //do nothing } } }
  • 19. OTHER PLAYERS LASERS function otherLasers() { for(var i = 0; i < other_lasers.length; i++) { if(other_lasers[i][0] < player.x + w && other_lasers[i][0] > player.x - w ) { if(other_lasers[i][2] == 1) { other_lasers[i][0] -= laser_v; } else if(other_lasers[i][2] == 0){ other_lasers[i][0] += laser_v; } else { other_lasers[i][1] -= laser_v; } drawLasers(other_lasers[i][0], other_lasers[i][1],other_lasers[i][2]); } else { other_lasers.splice(i,1); } } }