Calculating side of intersecting rectangle in collision

Hi all,
I'm trying to determine the side of a rectangle in which a colliding object has intersected with it (i'm working on some bouncing bullet code)
anyway, this is what I have so far..
I know, the bounding rectangle of the object being hit (tile)
(lets say 0,0,64,64 (top, left, width, height))
I know the projectile is moving 5 pixels per update and has a bounding box of pos.X, pos.Y, 16, 16
So when the bullet and tile collide, the rectangles intersect and so I know a collision has happened
but I want to now know which side of the tile object was intersected so i can do
If top or bottom is the intersecting side then reflect the Y velocity of the bullet (but leave the X projectile)
if left or right is intersected then reflect X and not Y
This should then give me this effect
TTTTTT
or
\ .T
.\ T
./ T
/. T
but to get that effect I need to know which side of the tile was intersected.
I also know the position of the bullet at collision and i know the last 12 positions leading up to collision (as i store them in an array for a bouncing action upon collision of other objects such as the player)
so from that I could work out the trajectory of the bullet through the bounding rectangle of the tile (even though I dont know how but I'm sure mathematics can be my friend on that one :p)
with all this knowledge, is there a way to achieve what I'm trying to do?
thanks
Edited by: harveyball on 05-Jun-2009 14:43

Hi again,
so i've found an algorithm to do my intersection and I've implemented a quick php version of the intersection code
which is
function intersectLine($line1A, $line1B, $line2A, $line2B)
     $insersectionPoint=array();
     $A1 = $line1B['y']-$line1A['y'];
     $B1 = $line1A['x']-$line1B['x'];
     $C1 = $A1 * $line1A['x'] + $B1 * $line1A['y'];
     $A2 = $line2B['y']-$line2A['y'];
     $B2 = $line2A['x']-$line2B['x'];
     $C2 = $A2 * $line2A['x'] + $B2 * $line2A['y'];
     $det = $A1 * $B2 - $A2 * $B1;
    if($det == 0)
          $insersectionPoint=array("x"=>-1, "y"=>-1);
     else
        $insersectionPoint['x'] = ($B2 * $C1 - $B1 * $C2) / $det;
        $insersectionPoint['y'] = ($A1 * $C2 - $A2 * $C1) / $det;     
     return $insersectionPoint;
     }however, i only want to know if the lines between the given points have actually touched (not the potential of the line if infinity extended)
My code will return an intersection even if the point hasnt reached that part of the line.
Can someone help me with the mathematical bit of doing the min and max of the points to work out the actual collision of lines.
I found this snippet of data from google
This gives you the location of the intersection of two lines, but what if you have line segments, not lines. In this case, you need to make sure that the point you found is on both of the line segments. If your line segment goes from (x1,y1) to (x2,y2), then to check if (x,y) is on that segment, you just need to check that min(x1,x2) ≤ x ≤ max(x1,x2), and do the same thing for y. You must be careful about double precision issues though. If your point is right on the edge of the segment, or if the segment is horizontal or vertical, a simple comparison might be problematic. In these cases, you can either do your comparisons with some tolerance, or else use a fraction class.
which is obviously what i want to do but I dont understand what this means
min(x1,x2) ≤ x ≤ max(x1,x2)
what exactly does ≤ x ≤ mean?
Can someone aid in writing the simplified version of the algorithm?
(java or pseduo is fine :) i just wrote my test function in php because it was quicker)

Similar Messages

  • Calculating points of intersection

    Hello,
    Do you guys know a method for calculating points of intersection for 2 axis shapes such as a circle.
    like if you had
    (3^2)+(4^2)=(5^2)
    and
    (6^2)+(8^2)=(10^2)
    and you wanted to calculate the points of intersection.....anyone know how i could do that?
    thanks
    hwrd

    does it not?
    import java.*;
    import javax.swing.*;
    public class Intersect extends Object {
         String xone, yone, xtwo, ytwo;
         String radiusone, radiustwo;
         double xoneint, yoneint, xtwoint, ytwoint;
         double radiusoneint, radiustwoint;
         double d, rsums,a,z,h, newa, newh, newsqrth,newhsqrt;
         double newxoneint, newyoneint,newxtwoint, newytwoint,sqrtpntone,sqrtpnttwo;
         double radiusoneintpow, radiustwointpow, dpow;
         double xthreepositive, xthreenegative,ythreepositive, ythreenegative;
         double newxthreepositive, newxthreenegative,newythreepositive, newythreenegative;
         public static void main (String []args)
              Intersect i = new Intersect();
              i.CircleDefinition();
         public void CircleDefinition()
                   xone = JOptionPane.showInputDialog("Please enter x1");
                   yone = JOptionPane.showInputDialog("Please enter y1");
                   radiusone = JOptionPane.showInputDialog("Please enter r1");
                   xtwo = JOptionPane.showInputDialog("Please enter x2");
                   ytwo = JOptionPane.showInputDialog("Please enter y2");
                   radiustwo = JOptionPane.showInputDialog("Please enter r2");
                   xoneint = Double.parseDouble(xone);
                   xtwoint = Double.parseDouble(xtwo);
                   yoneint = Double.parseDouble(yone);
                   ytwoint = Double.parseDouble(ytwo);
                   radiusoneint = Double.parseDouble(radiusone);
                   radiustwoint = Double.parseDouble(radiustwo);
                   DistanceCalculator();
         public void DistanceCalculator()
              newxoneint = Math.pow((xtwoint-xoneint),2);
              newyoneint = Math.pow((ytwoint-yoneint),2);
              d = Math.sqrt((newxoneint+newyoneint));
               *getting the basics working first and then i'll add these functions in later
               *newxoneint =Math.pow(xoneint, 2);
              newxtwoint =Math.pow(xtwoint,2);
              newyoneint = Math.pow(yoneint,2);
              newytwoint = Math.pow(ytwoint,2);
              sqrtpntone =Math.sqrt((newxoneint+newyoneint));
              sqrtpnttwo = Math.sqrt((newxtwoint+newytwoint));
              d= (sqrtpnttwo-sqrtpntone);
              z = radiusoneint+radiustwoint;
              /*if(d>z)
                        JOptionPane.showMessageDialog(null,"i'm sorry but no exist, the circles are separate.");
                        System.exit(0);
              else if (d<z)
                   JOptionPane.showMessageDialog(null, "Your cirlces have no intersection because one is contained in the other");
              System.exit(0);
              IntersectCalculations();
         public void IntersectCalculations()
              radiusoneintpow = Math.pow(radiusoneint,2);
              radiustwointpow = Math.pow(radiustwoint,2);
              dpow= Math.pow(d,2);
              a = (((radiusoneintpow)-(radiustwointpow)+(dpow))/(2*d));
              newa = Math.pow(a,2);
              h = Math.sqrt((radiusoneintpow - newa));
              newhsqrt = Math.sqrt(h);
              IntersectFinalCalculation();
         public void IntersectFinalCalculation()
              newxthreepositive = ((xtwoint) + (newhsqrt*(ytwoint-yoneint)/d));
              newxthreenegative = ((xtwoint) - (newhsqrt*(ytwoint-yoneint)/d));
              newythreepositive = ((ytwoint) + (newhsqrt*(xtwoint - xoneint)/d));
              newythreenegative = ((ytwoint) - (newhsqrt*(xtwoint - xoneint)/d));
               *don't floor them make sure they work and then start rounding
               *newxthreepositive = Math.floor(xthreepositive);
              newxthreenegative = Math.floor(xthreenegative);
              newythreepositive = Math.floor(ythreepositive);
              newythreenegative = Math.floor(ythreenegative);*/
              DisplayResults();
         public void DisplayResults()
              JOptionPane.showMessageDialog(null, "your circles intersect at \n\n"+newxthreepositive+","+newythreepositive+"\n\nand\n\n"+newxthreenegative+","+newythreenegative);
              CircleDefinition();
    }

  • Rectangles with colors

    <mx:Canvas id="b1" x="10" y="10" height="40" width="300" borderStyle="solid" borderColor="black"/>
    to add rectangles side by side inside this canvas i wrote the following code
    for(var i:int=b1.x;i<b1.x+b1.width;i=i+15)
                        var line1:UIComponent = new UIComponent();
                        var lineThickness1:Number = 1;
                        var lineColor1:Number = 0x000000;
                        var lineAlpha1:Number = 1;
                        line1.graphics.lineStyle(lineThickness1,lineColor1,lineAlpha1);
                        line1.graphics.moveTo(i,b1.y);
                        line1.graphics.drawRect(i,b1.y,15,b1.height);
                        this.addChild(line1);
    now I want to fill those rectangles with colored rectangles starting to ending
    i pass the units then units*15 will be calculated and the covered rectangles will be populated with colored rectangles for that i wrote the following code
                             var c:UIComponent = new UIComponent();
                            var xposstr:String = arr1.getItemAt(arr1.length).toString();
                            var xpos:int = parseInt(xposstr);
                           c.graphics.beginFill(0xFFCC00,1);
                            c.graphics.drawRect(xpos,0,numUnits*15,b1.height-2);
                            c.graphics.endFill();
                            b1.addChild(c);
                            arr1.addItem(c.x+numUnits*15);
    arr1 is the ArrayCollection
    but iam not getting the required output

    This code draws rectangle (random background color),
    var colors: Array = [0x0000FF, 0x00FF00, 0xFF0000, 0xFF00FF]
    for(var i: int = 0; i < b1.width; i = i + 15) {
         var lineThickness1:Number = 1;
         var lineColor1:Number = 0x000000;
         var lineAlpha1:Number = 1;
         var bgColor: uint = colors[Math.floor(Math.random() * colors.length)];
         var g: Graphics = b1.graphics;
         g.lineStyle(lineThickness1,lineColor1,lineAlpha1);
         g.beginFill(bgColor, 1.0);
         g.moveTo(i, 0);
         g.drawRect(i, 0, 15, b1.height - 1);
         g.endFill();

  • Help with Collision

    I'm trying to make a game, and I'm stuck at collision. I'm trying to get a line at about a 45 degree angle to "destroy" the objects it collides with. I tried doing rectangle-intersecting-rectangle type things (I would need a diagonal rectangle), but I'm having problems with that... I tried doing something like this:
    r1 = new Rectangle( lineLocation, 0, 448, 448 );
    r1.add( lineLocation, 448 );
    r1.add( lineLocation+ 10, 448 );
    r1.add( 465 + lineLocation, 0 );
    r1.add( 480 + lineLocation, 0 );to create the rectangle, but that didn't seem to work. What am I doing wrong?
    I also used a collision boolean, which was set "true" with collide=r1.intersects(r2);Or would it be better to do a line/rectangle intersection? I tried doing that too, but that didn't work either. It might be better to go with the rectangles, though, because the line has width to it. Any suggestions on how I should do this? Thanks.

    the angles are all still 90 degrees. But maybe it's not possible to make those
    as rectangles.A Rectangle is defined by a Top-Left corner, a width and height.
    You could use an AffineTransform to rotate the Rectangle
    public class ShapeTransform
       public ShapeTransform()
          // define the shape
          Rectangle r = new Rectangle(0, 0, 100, 100);
          System.out.println(r);
          // transformation of 45 degrees anticlockwise around point (0,0)
          AffineTransform at = AffineTransform.getRotateInstance(
                Math.toRadians(45), 0, 0);
          Shape newR = at.createTransformedShape(r);
          PathIterator pi = newR.getPathIterator(new AffineTransform());
          while (!pi.isDone())
             double[] segment = new double[6];
             pi.currentSegment(segment);
             for (int i = 0; i < 2; i++)
                if (Math.abs(segment) < 0.001)
    segment[i] = 0;
    System.out.print(segment[i] + ",");
    System.out.println();
    pi.next();
    public static void main(String[] args)
    new ShapeTransform();
    Cheers,
    evnafets

  • Is there any way to create a shadow in both sides of a box?

    Hi,
    is there any way to create a shadow in both sides (opposite) of a box? I just can create the shadow in one side..
    If not, is that possible in CS6?
    CS5.
    Regards

    You can definitely show an inner shadow on just one side of a rectangle.  You just need to turn the blur down to 0 to prevent it from leaking to the nearby sides.  Then set the angle to an exact multiple of 90, like 270 to put the shadow on the top side of the rect.
    This file has some examples: http://johndunning.com/fireworks/scratch/Shadowed%20Elements.png
    If you're trying to simulate a rectangle with different border colors or widths, this auto shape can make that easy: http://johndunning.com/fireworks/about/MultiBorderRect

  • Drawing object on the intersections point of 2 lines.

    hi guys, im very new in actionscrip , please give me some guidance.
    i'm doing this project , about 2 lines intersecting each other(the 2 lines are not always on the same position) . i try to find the intersections point using collision detection method but how do i place an object on the intersections point?
    if(line1.hitTestObject(line2)) //  so this is how we find the intersection point but we do not know how to draw/place an object on the  intersection point.

    then it's easier to calculate the intersection algebraically:
    function intersectionF(x1:Number,y1:Number,x2:Number,y2:Number,x3:Number,y3:Number,x4:Number,y4:Number):Array {
         if (x1==x2) {
              if (x3==x4) {
                   if (x1==x3) {
                        return ["line1"];
                   } else {
                        return [null];
              } else {
                   // line 1 vert, line 2 not
                   var m2:Number = (y3-y4)/(x3-x4);
                   var b2:Number = y3-m2*x3;
                   return [x1,m2*x1+b2];
         } else {
              // line 1 not vert
              if(x3==x4){
                   // line 2 vert
                   var m1:Number = (y1-y2)/(x1-x2);
                   var b1:Number = y1-m1*x1;
                   return [x3,m1*x3+b1];
              } else {
                   // line 2 not vert
                   m1 = (y1-y2)/(x1-x2);
                   b1 = y1-m1*x1;
                   m2 = (y3-y4)/(x3-x4);
                   b2 = y3-m2*x3;
                   var x:Number = (b2-b1)/(m1-m2);
                   return [x,m1*x+b1];

  • Number keys on calculator key board

    For some reason the number keys on the calculator side of the key board are not working. I can not use them to conduct any calculations on the calculator. Can anyone help??

    Hi duggg,
    updating your OSX to the latest version as baltwo proposed is a good idea.
    Also, maybe you accidentally activated Mouse Keys http://docs.info.apple.com/article.html?path=Mac/10.5/en/8421.html
    And if not, have you tried the 'Clear key' (the on above the '7'-key on the Numpad)
    Regards
    Stefan

  • Left side drop shadow

    I have a background rectangle at 1278 x 1000 px.  I have my page at 1074x 1000 pixels.  I have a drop shadow effect on the right side of the page.  I want the same drop shadow effect on the left hand side of the rectangle that is my 1074 web page.  It gives it a nice 3D effect.  How would I get it on the left since I selected the rectangle and the drop shadow only works on the right side and bottom I guess.  I can't see the bottome since it is off the art board.   I don't want it on the bottom edge anyway.  Only the left and right sides.  In the drop shadow panel I only see the x & y access and shades selections?
    thanks,

    Just add another instance of the Drop Shadow Effect from the effects menu. Left and right are controlled by the X offset (positive to the right, negative to the left); up and down by the Y offset (positive down, negative up) either can be 0.

  • Changing Thickness of Lines Created with Rectangle Tool in CS2?

    I am trying to change the thickness of the lines for a rectangle drawn using the Rectangle Tool in Photoshop CS2.
    I can not figure out how to change the thickness of the lines of the four sides of the rectangle before I draw the rectangle using the Rectangle Tool or after the Rectangle has been drawn. The same problem seems to occur when using the Polygon Tool, Ellispse Tool, etc.
    I can transform the rectangle to make it bigger or smaller, etc. but it seems like I should be able to vary the thickness of the lines for a rectangle.
    Is this task possible in Photoshop?  It's simple in Illustrator - this seems like it should be a pretty simple task in P-shop.  I have looked on Google and in Help for P-shop CS2 for an answer but can not locate a solution.  Am I not seeing something really obvious?
    Any help is greatly appeciated.
    Thanks!

    Hi,
    Thanks for your reply.
    I am making a path.  That said, in Photoshop CS2 I don't see where I can select a brush size once I have selected the Rectangle Tool to increase the desired thickness or weight of the path for that rectangle.  Since I am creating a path why would I use/select a brush size?  I have attached a screen shot which shows what I am seeing when I select the Rectangle Tool and attempt to change the thickness of the path. The attached image aslo shows what I am trying to accomplish.  I don't see where I can select the weight or thickness - even when I right-click with the mouse, etc.  Even if I try to change the Style from the Option bar it seems overly complex for such a simple task.
    When using the Line Tool in Photoshop CS2 you do have an option to change the line thickness or weight but when I click on the Rectangle Tool that option for changing the the line thickness or weight disappears.
    I realize P-shop CS2 isn't specically designed for drawing, like Illustrator, but what I am trying seems simple.
    Any other suggestions would be greatly appreciated.
    Thanks for your time!

  • Adding a rectangle & a followup question regarding layering

    I want to simply draw a rectangle on a a location on photograph or file and just see the outline of the rectangle in a color of my choice...I dont want the rectangle filled in with the color...just the outline. I would like to have all sides of the rectangle the same width ....it would be nice to be able to determine that width if possible. What I am trying to do is to create rectangular locations on a photograph and then add text to that identified area...
    In a follow up question it appears that each time I add text from one location on the photo and go to another area to add text...a new layer appears. It would be nice to be able to add various rectangles and areas of text without having a new layer appear for each entry...is that possible?

    Use the Rectangular Marquee tool to define the rectangle. Then use the Stroke command to draw the line around it.
    You can flatten the image or merge layers, but there is no way that you can stop them being created when you create shapes or text. I don't think that being able to do so would be useful for many people.

  • Trying to make rectangle fade to lighter colour from left to right

    Hey, having trouble making the colour of my rectangle
    gradually get lighter to a point on the right side of the
    rectangle. Anyone seen this effect before? help!!??

    Change the fill from Solid to Linear Gradient from the
    Properties Panel
    > Fill Category.
    If you need the rectangle to fade out go to Commands >
    Creative > Fade
    Image.
    alex
    defender_nz wrote:
    > Hey, having trouble making the colour of my rectangle
    gradually get lighter to a point on the right side of the
    rectangle. Anyone seen this effect before? help!!??

  • Corner effects on one side only

    Hi, I hope someone can help me QUICK!
    I want to apply rounded corners to one side of a rectangle (2 corners); the other side (2 corners) I want to remain square.
    I tried to add anchor points and pull one side to square it off, but it's still rounded... What to do?
    I read in one of the forum posts to use the "corner effects sample script" -- I guess I have no idea what this is.
    Any other solutions? Help please!

    It should work but here's a CS3 procedure.
    Create your rectangle. Add the corner options using whatever setting you
    like.
    Keep it selected and open the pathfinder panel. Click the convert to
    rounded rectangle button.
    Draw a new rectangle and place it on the edge you want to have square
    corners. Click the subtract button.
    Voila!
    Bob

  • How to insert an image into lower third rectangle title?

    I'm creating a new title for news videos for a local newspaper's website.
    I've created a white lower third rectangle and I want an image of the newspapers logo to be inside of the white lower third rectangle.
    I'm trying to drag the image into the title workspace but it wont allow me to do so......
    How can I get this image of the newspapers logo inside of the white lower third rectangle?
    Thanks,
    Any help appreciated!
    Jonathan.

    Hi Dave,
    Great advice! That's working fine.
    But....my white lower third rectangle has a fill opacity of 88%. When I've inserted the newspaper's logo into this rectangle, obviously the logo (which is white with blue text) has an opacity of 100%. But when I lower the logo opacity to 88% I lose the logo's white, but also the actual text of the logo too which is a problem.
    So I'm now thinking, is it possible to lower fill opacity from left to right in my rectangle? If so, this would allow the left hand side of my rectangle to stay at 100% fill opacity, which would match the white fill of the newspapers logo, and I could gradually reduce the opacity as the rectangle goes right, fading out towards the end.
    Is it possible to use fill opacity in a left to right motion?
    Thanks Again!

  • Moving a circlewithin a rectangle

    Hi i am currently working on a gauge and have one such that a rectangle is filled with the fill method in paint with certain values passed to it .
    I would like to now develop a new gauge whereas a filled circle or ball would move along the inside of the rectangle instead of it being filled with color
    I should also state that some values here are run in a thread and just called in this draw method. The repaint is also in a thread hence gives the
    effect that the guage is moving constantly
    the following code represents my draw method to post all the classes here would be really alot so any help with the draw method is appreciated
    public void draw(Graphics2D g) {
    // set up variables to use
            g.translate(getX(),getY());
            int w = getWidth()/2;
            int h = getHeight();
            int totalRange = 100-0;
            int units = h/totalRange;
            int value = getICUMonitor().getDiaSensor().getDiastolic();
            int valueHeight = value*units;
            int valueY = h-valueHeight;
            // setup a gradient paint
            GradientPaint redtowhite = new GradientPaint(5, 5, Color.blue, 5, 5,Color.blue);
            g.setPaint(redtowhite);
            // drawing the actual rectangle
            g.setColor(Color.LIGHT_GRAY);
            g.draw(new Rectangle2D.Double(0,0,w,h));
            // filling the rectangle with a color
            g.fill(new Rectangle2D.Double(0,valueY,w,valueHeight));
            // this draws small lines along the side of the rectangle as markers
            for(int i=0;i<getHeight()+10;i+=10){
                g.drawLine((int)w+2,i,(int)w+6,i);
            // here is just putting the numbers 0 on the first marker and 100 on the last
            g.drawString("100",(int)w+14,0);
            g.drawString("0",(int)w+14,(int)getHeight());
            g.translate(getX()*-1,getY()*-1);
        }

    I would like to now develop a new gauge whereas a filled circle or ball would move along the inside of the rectangle instead of it being filled with colorThis is really simple, you just have to replace your fill Rectangle call with a drawRect and fillOval calls.
    g.drawRect(0, valueY, w, valueHeight);
    g.fillOval(w/2-8, valueY, 16, 16);// drawing a circle of width 16 on the top middle of rectangleAnd yes SSCCE would be helpful, if your problem is not as simple as I thought.
    Thanks!

  • Drawing a rectangle...corectly!

    If i try to draw a rectangle at the point 0,0 if works fine, but when i start moving the point around, the right side of the rectangle disapears for no apparent reason. so it looks like this
    |
    |
    |
    |____________________
    a three sided box. why is it doing this? thank you so much for any help, this is really frustrating me!

    My only guess is that you are drawing this rectanlge inside a component which is just big enough to fit the rectablge, but as soon as you move the position of the rectangle it's getting clipped off the edge of the component.

Maybe you are looking for