2

$player is at the center of the screen and can be moved at 360 following the mouse angle direction continuously, when I move it I also change the position of $map in the opposite direction, maintaining the player at center and creating a "moving" effect in the map...

This is fired on mousedown:

var top1 = $map.offset().top;
var left1 = $map.offset().left;
var top2 = ($player.offset().top - $player.height()/2) - ($map.offset().top);
var left2 = ($player.offset().left - $player.width()/2) - ($map.offset().left);

if(interval1 == 'false'){
    interval1 = setInterval(function(){
        var speed = 1;
        var deltaX = Math.cos(angle * Math.PI / 180) * speed;
        var deltaY = Math.sin(angle * Math.PI / 180) * speed;

        $map[0].style.left = (left1 -= deltaX)+'px';
        $map[0].style.top = (top1 -= deltaY)+'px';
        $player[0].style.left = (left2 += deltaX)+'px';
        $player[0].style.top = (top2 += deltaY)+'px';
    }, 1);
}

I do this on mouseup:

clearInterval(interval1);
interval1 = 'false';

The problem is that every time I fire the mousedown it adds some little gaps to the player so at every click it moves a bit from the center...

How can I fix this problem? I was not able to figure out what generates the gap...

neoDev
  • 2,879
  • 3
  • 33
  • 66
  • It may not solve your problem (your example isn't an [mcve]) but don't move both objects, you're compounding errors from converting floating point to integers anyway - why make it worse? Just move the map. – Tibrogargan Jun 28 '16 at 00:55
  • The code shown never clears the interval. If you create a new interval on every mousedown event *without* cancelling the previous interval then you'll have problems. – nnnnnn Jun 28 '16 at 00:55
  • @Tibrogargan I need to update the player position, I cannot only move the map. How can I fix floating/intergers conversion? – neoDev Jun 28 '16 at 01:04
  • @neoDev why can't you just move the map? The screen coordinates of the player's icon has very little to do with where the player is located on the map. When the player moves their map coordinates by clicking just move the map so that the player's new map coordinates are under the screen coordinates. Don't move the player's icon at all. `move map "west" 10 pixels` gives effectively the same result as `move map "west" 5 pixels, move player "east" 5 pixels` or `move player "east" 10 pixels`. Different story if you try to move 11 pixels. – Tibrogargan Jun 28 '16 at 02:25

2 Answers2

1

You might be running in to the gap problem due to your setInterval delay time being too short. The browser can't draw each step in between that fast. Try testing it with 100 instead of 1

webdevdani
  • 1,062
  • 7
  • 11
0

If you have the 2D game - for each object you must to store global coordinates, that are map-position independent. Then by the object coordinates and "camera position" you can compute precise rendering coordinates of objects .

Alexander Goncharov
  • 1,572
  • 17
  • 20