Question

I'm using Cocos2D for iPhone to build up a game.I have a grid on the screen drawn by horizontal and vertical lines.(I did it with CCDrawNode) As you might guess there're lots of intersection points in there, I mean the points where horizontal and vertical lines intersect. With every touchBegan-Moved-Ended routine I draw a line, a bolder and different color line. In touchesMoved method I need to find the intersection point nearest to the current end point of the line and stick the line end to that point. How can I do that? I have one idea in my mind which is to add all the intersection points to an array when drawing the grid, iterate through that array and find the closest one. But I think this is not the best approach. You have any better ideas?

Was it helpful?

Solution

Assuming it is a normal grid with evenly spaced lines (e.g. every 10 pixels apart), you are much better off using a formula to tell you where an intersection should be.

E.g. given end point X/Y of 17,23, then x(17)/x-spacing(10) = 1.7, rounds to 2. 2*x-spacing = 20. y/y-spacing=2.3 -> 2*20 = 20. Thus your intersection is 20,20.

EDIT: more detailed example, in C# as that's what I use, if I get time I'll write an Objective-C sample

// 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);
}

NOTE: the code above is left quite verbose to help you understand, you could easily re-write it to be cleaner

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top