
-----------------------------------
Mr. T
Sat Sep 24, 2005 3:03 pm

Collision Detection
-----------------------------------
Given the following code, can you show me how to do collision detection with the 1) whatdotcolour method 2) regular method.
And can you explain why the ball looks so jittery.

View.Set ("offscreenonly")
const RADIUS : int := 5
const NUM_BALLS : int := 1
var x, y, dx, dy, clr : array 1 .. NUM_BALLS of int

 for i : 1 .. NUM_BALLS
            x (i) := Rand.Int (RADIUS, maxx - RADIUS)
            y (i) := Rand.Int (RADIUS, maxy - RADIUS)
            dx (i) := Rand.Int (-3, 3)
            dy (i) := Rand.Int (-3, 3)
            clr (i) := Rand.Int (1, 15)
        end for

loop
    for i : 1 .. NUM_BALLS
        if x (i) + dx (i) < RADIUS or
                x (i) + dx (i) > maxx - RADIUS then
            dx (i) := -dx (i)
        end if
        if y (i) + dy (i) < RADIUS or
                y (i) + dy (i) > maxy - RADIUS then
            dy (i) := -dy (i)
        end if
        x (i) := x (i) + dx (i)
        y (i) := y (i) + dy (i)
        Draw.FillOval (x (i), y (i), RADIUS, RADIUS, red)
        Draw.FillBox (300, 200, 200, 300, blue)
    end for
        View.Update
    cls
end loop


-----------------------------------
Cervantes
Sat Sep 24, 2005 6:03 pm


-----------------------------------
1) Don't go there.  There are two reasons I say this.  First, it's complicated for this sort of thing.  Ideally, you would check a grid of pixels in front of each ball with a width equal to that of the ball and a depth equal to the speed (vector addition of x and y components of velocity) of the ball.  This is complicated by the fact that the ball can be moving in 24 different directions.

2) Use the distance formula.


if Math.Distance (  x (j), y (j), x (k), y (k)  ) < radius (j) + radius (k) then
    %Handle Collision
end if


(This is assuming you are checking for collisions between different, not with that blue square you've got in the middle (?) )

On that note, the blue box drawing method should be outside the for loop.  There's no point in drawing a box multiple times.  (Yes, your for loop only executes once, but that can be changed easily enough.)

Lastly, it doesn't look jittery to me.  It actually runs very fast, as there is no delay.

If you are looking to do collisions with the box, use some if statements.

if x (i) + RADIUS >= box_x1 and y (i) + RADIUS >= box_y1 and x (i) - RADIUS = box_x1 and y (i) + RADIUS >= box_y1 and x (i) - RADIUS =200 and y(i)= or = 200 and x (i) + dx (i) = 200 and y (i) 