瓷砖所在的网格中的位置 [英] Where in the grid the tile belongs

查看:61
本文介绍了瓷砖所在的网格中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建虚拟网格32x32为< div> 示例:

If I created a virtual grid 32x32 as a <div> example:

我想填写其中一个瓷砖点击上的黑匣子我到目前为止:

I want to fill one of the tile with a black box on click I have so far this:

var _proto = {
    id:0,
    x:0,
    y:0
}

var objects = [];

$(".test").on("mousedown", function(e) {

    var offset = $(this).offset();
    var prex2 = 0, prey2 = 0;

    prex2 = _proto.x = e.pageX-offset.left;
    prey2 = _proto.y = e.pageY-offset.top;
    _proto.id = (_objects.length)?_objects[_objects.length-1].id+1:0;

    // Add to grid (not sure how to get proper cordinates)
    $("<div style='display:absolute;width:32px;height:32px;background:black'></div>")
        .css("top","")
        .css("left","")
        .appendTo("#maindiv");

});

我的坐标为 prex2 ,以及 prey2 用户点击的位置,但我怎么知道将它放在网格中的哪个位置?我确定有一个简单的数学方程,但我无法弄明白。

I have the coordinates as prex2, and prey2 where the user clicked, but how do I know where to put it in the grid? I'm sure there a simple math equation but I can't figure it out.

推荐答案

这是地图编辑器的一个片段我几个月前就开始工作了。它可能会帮助您解决自己的代码。

Here's a snippet from a map editor that I was working on a few months back. It might help you grapple with your own code.

mapBlanket.addEventListener("mousedown", function(e) {
    var sideWidth = document.getElementById("mapSide").offsetWidth;
    var headHeight = document.getElementById("system").offsetHeight + 32;
    var clickX = e.pageX - mapBlanket.offsetLeft - sideWidth + mapBlanket.parentNode.scrollLeft;
    var clickY = e.pageY - mapBlanket.offsetTop - headHeight + mapBlanket.parentNode.scrollTop;
    var tileX = clickX - (clickX % map.grid);
    var tileY = clickY - (clickY % map.grid);
    if (paintOn == 5) {
        eventThis(tileX, tileY);
    } else if (paintOn < 5) {
        paintThis(tileX, tileY);
    }
    ...
}

作为参考,map.grid是32,与你的相同。我只是在文件顶部的对象中定义了一个好位。

For reference, the map.grid was 32, same as yours. I just had a good bit defined in an object at the top of the file.

这篇关于瓷砖所在的网格中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆