Change the position of an object on a map

Asked

Viewed 341 times

0

Guys, I need a logic that, by detecting whether the value of x, y changed, change the position of an object on the map.

I have a map that contains 50x50 tiles, and in these Tiles there are objects that I can move using the code below:

var playerx = 10;
var playery = 15;

function drawMap() {
    for (i = 0; i < map.length; i++) {
        for (j = 0; j < map[i].length; j++) {
            var drawTile = map[i][j];
            var drawObj = objectMap[i][j];
            var xpos = (i-j) * tileH + mapX;
            var ypos = (i+j) * tileH/2 + mapY;

            ctx.drawImage(tileImg[drawTile], xpos, ypos);

            if (drawObj) {
                ctx.drawImage(objectImg[drawObj-1], xpos, ypos - (objectImg[drawObj-1].height));
            }
        }
    }
}

To add the object I use this property:

objectmap[playerx][playery] = 1;

And to remove I use the function delete:

delete objectmap[playerx][playery];

What happens is that the object is in positions 10 and 15 which are the values of the variables playerx and playery, but I have a function that takes the mouse position and when clicking changes the value of playerx and playery, happens that as the value of the function changes, it adds objects in the map, without removing the last.

So the map gets multiple objects, but I want the object to stay just where the values of the variables point.

You know how to do that with a if or otherwise?

  • Can you review the question and clarify the question better? can you add a jsFiddle to make it clearer?

  • and because I’m on the tablet, and how do I put the code tags on stackoverflow?

  • I edited the question for you, you can put codes using the symbol `

  • no one knows how to do no?

  • Attention moderators can delete my post and topic as I’ve solved this problem.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.