0

我正在使用 Cocos2D for iPhone 来构建游戏。我在屏幕上有一个由水平线和垂直线绘制的网格。(我用 CCDrawNode 做的)你可能猜到那里有很多交叉点,我的意思是水平线和垂直线相交的点。在每一个 touchBegan-Moved-Ended 例程中,我都会画一条线,一条更粗、颜色不同的线。在 touchesMoved 方法中,我需要找到离线的当前端点最近的交点并将线端粘贴到该点。我怎样才能做到这一点?我有一个想法,就是在绘制网格时将所有交点添加到一个数组中,遍历该数组并找到最接近的一个。但我认为这不是最好的方法。你有更好的想法吗?

4

1 回答 1

3

假设它是一个具有均匀间隔线的普通网格(例如,每 10 个像素间隔),你最好使用一个公式来告诉你应该在哪里交叉。

例如,给定端点 X/Y 为 17,23,然后 x(17)/x-spacing(10) = 1.7,四舍五入为 2. 2*x-spacing = 20. y/y-spacing=2.3 -> 2* 20 = 20。因此,您的交点是 20,20。

编辑:更详细的示例,在 C# 中,因为这就是我使用的,如果我有时间,我将编写一个 Objective-C 示例

// defined somewhere and used to draw the grid
private int _spacingX = 10;
private int _spacingY = 10;

public Point GetNearestIntersection(int x, int y)
{
    // round off to the nearest vertical/horizontal line number
    double tempX = Math.Round((double)x / _spacingX);
    double tempY = Math.Round((double)y / _spacingY);

    // convert back to pixels
    int nearestX = (int)tempX * _spacingX;
    int nearestY = (int)tempY * _spacingY;

    return new Point(nearestX, nearestY);
}

注意:上面的代码很冗长以帮助您理解,您可以轻松地重写它以使其更清晰

于 2013-05-02T02:43:17.850 回答