1
\$\begingroup\$

So I'm testing a few things in Javascript and something I was testing was making the camera follow the player. When I move the player, instead of the dots going away from the player, they follow the player and it looks very strange.

Here is the code: https://codepen.io/anon/pen/wLgEPO?editors=0010

Move the player using the arrow keys.

Thanks.

\$\endgroup\$
1
\$\begingroup\$

You just inverted the signs. The player's position should be the negative one and the canvas position, the positive one:

c.translate(-p.x, -p.y);
c.translate(canvas.width/2, canvas.height/2);

The reason for this is that canvas.translate makes a given point be considered (0,0) for all other drawing operations. The player is going to be rendered at position p.x and p.y. So if you want to make the player always stay at the point (400, 400) or (canvas.width/2, canvas.height/2) you need to make (0, 0) become a value that added the current player position it will become (400, 400). That value is: (400 - p.x, 400 - p.y). You were previously subtracting 400 from the player position when the right is to subtract the player position from 400. A more consize code would be to replace those 2 lines with this one:

c.translate(canvas.width/2-p.x, canvas.height/2-p.y);
\$\endgroup\$
  • \$\begingroup\$ Thanks, Worked just how I wanted. \$\endgroup\$ – Luke460 Jun 21 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.