• Fast 2D Collision Detection in XNA

    As shown in the YouTube video in the post Fast collision detection in XNA, I made a quick way of doing near pixel perfect collision detection in XNA that does not get slowed down by rotating the object. This algorithm first checks the bounds of the object that scales based on the rotation of the content(as shown in Re-scaling a rectangle based on the rotation of it’s content), before checking for line intersection (see Determining if two lines intersect).

    The whole idea is to generate lines around the object as this is much faster then checking pixel by pixel and can easily be rotated as they only consist of two points. This is done only once when first loading the image.

    Tracing the outlining of the object using 5 segments

    Once the outlining has been traced, we generate lines between them to give us the approximate outlining. In this case 5 segments has been used to better illustrate what is being done. The mesh we end up with should look something like the following.

    » Continue reading

  • Determining if two lines intersect

    Today we are going to take a look at intersecting lines. There are some information on this scattered around the internet, but a good example is hard to find. The uses for this is mainly in 2D, it can be applied to lighting, physics and all other applications using rays.

    Intersecting and non-intersecting lines

    To solve this, we want to convert our lines to the following form:

    This allows us to create an equation that we can solve, with no need for ray tracing or other techniques. Converting our lines to this form is pretty trivial, as shown below. We do this for both lines, giving us the equations for both.

    Now when we have the expression for both lines, first of all we want to find the determinant to check if the lines are exactly parallel (they never intersect). The lines are parallel if the determinant is equal to zero.

    » Continue reading

  • JQuery Tooltip

    Ever in need of more than just the standard abbr tooltip? A little while back I wrote just that. It can easily be made prettier, but it works as intended. What this does is listening for the mouseover and mouseout events and display a div with absolute positioning at the element’s location with the tooltip text.

    To add tooltips, the syntax would be like this:

    <a href="#" class="tooltip" data-title="Tooltip title" data-content="Tooltip text">The text you want tooltipped</a>

    This is what is looks like in action:

    Tooltip title and text The JavaScript code that does the work looks like this. As you can see, the listeners are registered and when the mouse hovers the element, it gets the data-title and data-content attributes from the <a> element.

    $(document).ready(function() {
        $('a.tooltip').mouseover(function(e) {
            var title = $(this).attr('data-title');
            var content = $(this).attr('data-content');
    		
            if(title != null && title.length > 0) {
                $('div#tooltip_content').html("<b>" + title);
    			
                if(content != null && content.length > 0) {
                    $('div#tooltip_content').append("</b><br /><br />" + content);
                }
    		
            } else if(content != null && content.length > 0) {
                $('div#tooltip_content').append(content);
    		
            } else {
                return;
            }
    
            $('div#tooltip_wrapper').css('left', $(this).position().left + 
                ($(this).width() / 4));
            $('div#tooltip_wrapper').css('top', $(this).position().top + 
                $(this).height());
            $('div#tooltip_wrapper').show();
        });
    	
        $('a.tooltip').mouseout(function(e) {
            $('div#tooltip_wrapper').hide();
            $('div#tooltip_content').html("");
        });
    });

    The full source code can be found here: tooltip_js.js. As always: If you have any questions, please let me know!

  • Drawing lines in XNA

    As there is no built in way of drawing lines in XNA(which is really weird), I thought that I should share this little snippet.

    public void drawLine(SpriteBatch spriteBatch, Vector2 p1, Vector2 p2, Texture2D texture)
    {
        float length = (float)Math.Sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y));
        spriteBatch.Draw(texture, new Vector2(p1.X, p1.Y), null, Color.White,
            (float)Math.Atan2(p2.Y - p1.Y, p2.X - p1.X),
            new Vector2(0f, 1.0f),
            new Vector2(length, 1f),
            SpriteEffects.None, 0f);
    }

    This function draws a line between p1 and p2, using the texture defined(yes, it needs to be a texture). The Color.White in the function, just specifies the clear color. I post this now, as it can be used with the upcoming how-to: Line intersection.

  • Re-scaling a rectangle based on the rotation of its content

    As you might have noticed in the video in my earlier post, the bounding box of the sprite is scaling based on the rotation. This is useful as it ensures that even if the content is rotated, it is always within the bounds of the rectangle. To illustrate this, take a look at the following photos:


    When we rotate the blue square, its bounds increases to the square in green. This is what we are trying to compensate for. The following formula gives us the delta x and y from the origin point.

    Using this formula, we find that dx’ = 4.24 and dy’ = 4.24. Please note that this formula will work for any sizes, I’m just using a square for simplicity. By applying this to code, we get the following in C#:

    public Rectangle getBoundsWithRotation(Rectangle rect, float angle)
    {
        Vector2 origin = new Vector2((float)rect.X + rect.Width / 2.0f, 
            (float)rect.Y + rect.Height / 2.0f);
    
        float dx = (float)Math.Abs(Math.Cos(angle)) * (rect.Width / 2.0f) + 
            (float)Math.Abs(Math.Sin(angle)) * (rect.Height / 2.0f);
        float dy = (float)Math.Abs(Math.Sin(angle)) * (rect.Width / 2.0f) + 
            (float)Math.Abs(Math.Cos(angle)) * (rect.Height / 2.0f);
    
        int x = (int)Math.Round(origin.X - dx);
        int y = (int)Math.Round(origin.Y - dy);
        int w = (int)Math.Round(dx * 2.0f);
        int h = (int)Math.Round(dy * 2.0f);
    
        return new Rectangle(x, y, w, h);
    }

  • Fast collision detection in XNA

    I have been helping a friend of mine with a way of doing quick 2D collision detection in XNA. One of the common problems with collision detection in 2D is when you rotate it. Most functions do pixel perfect collisions by parsing the whole images, as it can be tricky to get the correct pixels to compare with each other when you rotate the image. Modifying the texture itself is way too slow and should be avoided at all costs and I feel the same about checking every pixel.

    My solution parses the texture beforehand, generating either bounding lines or a line grid above the texture. When this is used with rectangle intersections as well, before doing the fine tests, it runs both fast and precise. The resolution of the lines can easily be specified for each texture and they work no matter what resolution you might use.

    I’ll get around to posting both the math and the code (when I get it cleaned up), but for now: here is a preview of the working concept.

subscribe via RSS