neoDev
neoDev

Reputation: 3049

Change position of an element and its parent in javascript

$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...

Upvotes: 2

Views: 157

Answers (2)

webdevdani
webdevdani

Reputation: 1102

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

Upvotes: 1

Alexander Goncharov
Alexander Goncharov

Reputation: 1662

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 .

Upvotes: 0

Related Questions