Search code examples
javascripthtmlcanvasgame-physics

Following camera with javascript/html canvas for game


    frameUpdate = ()=>{
        canvas = $("canvas")[0]
        c = canvas.getContext('2d')
        c.resetTransform()
        c.clearRect(0, 0, canvas.width, canvas.height);
        LocalPlayer.Move();//if player press arrow keys, changes X any Y values of local player

        c.translate(LocalPlayer.X - (canvas.width/2), LocalPlayer.Y - (canvas.height/2));//not works

        LocalPlayer.Update();//draws Local Player at own X and Y position to canvas
        PList.Update();//draws other players at own X and Y position to canvas


       if (LocalPlayer) {socket.emit('sendplayer',LocalPlayer);}//sends LocalPlayer's data to server
        requestAnimationFrame(frameUpdate)
    }
    requestAnimationFrame(frameUpdate)

i want to make a game like io games with socket.io and html/canvas but i cant make camera follows player, and i cant found any simple solution on internet so if you can, i want tell me how it works and what is wrong on my code

Thanks.


Solution

  • after several tests with codepen i was solve my own problem myself

    function update() {
      c.save();
      camerax = (canvas.width/2)-(playerx);
      cameray = (canvas.height/2)-(playery);
      mtt.innerText = "Camera Position:"+camerax+","+cameray+"\nPlayer Position:"+playerx+","+playery+"\nCanvas:"+canvas.width+","+canvas.height+"\n";
      c.clearRect(0, 0, canvas.width, canvas.height);
      c.translate(camerax, cameray);
    
       c.fillStyle = 'green';
      c.fillRect(playerx-25, playery-25, 50, 50);
      c.restore();
    
      requestAnimationFrame(update);
    }
    requestAnimationFrame(update);