Now you know how to move the object and as life has proved, every moving object will sooner or later collide with something. If the moving object is for example you, and you are lucky, you may collide with something soft, like bed, but sometimes you can also collide with hard stuff. Brick wall. Cement floor. Closed door. Many other unpleasantly hard items are out there in the wild world, only waiting to collide with you or other moving objects. So its good to your healt and generally wise to know which objects you may collide with in the future.

We know the movement vector of object. And we know the vector which makes up wall (ok, the wall looks like thin line, but you still need to be careful). We want to know if and when and where the moving object collides with the wall, or to rephrase it "where do two vectors intersect?"

First lets see when they dont intersect. Vectors cant intersect when they are parallel. And vectors are parallel when their unit-vectors are equal (dont have to be same direction, they can be opposite too):

(v1.dx==v2.dx and v1.dy==v2.dy) or 
(v1.dx==-v2.dx and v1.dy==-v2.dy)

If they are not parallel, then intersection happens sooner or later. Green line is movement vector with its start point p0, red line is the wall with its starting point p0 and blue line is vector between start points:

The coordinates of intersection point can be calculated like this:

v3={vx:v2.p0.x-v1.p0.x, vy:v2.p0.y-v1.p0.y};
var t=perP(v3, v2)/perP(v1, v2);
function perP(va, vb){
	pp = va.vx*vb.vy - va.vy*vb.vx;
	return pp;

First we find vector v3 between starting points. The function used here calculates perp product of 2 vectors. Perp product is similar to dot product only instead of first vector its normal is used. Dot product was:

dp = v1.vx*v2.vx + v1.vy*v2.vy;

and normal was:

v.rx = -v.vy;
v.ry = v.vx;

so when we replace the v1 with its normal we get:

pp = -v1.vy*v2.vx + v1.vx*v2.vy;

which is exactly what the function finds.

Ratio "t" between 2 perp products is exactly 1 when the intersection point is exactly at the end point of movement vector 1. If "t" is between 0 and 1 then the intersection point is on the vector. However, if the "t" is negative then the vectors have intersect sometimes in the past and if its bigger then 1, then the intersection happens sometimes in the future.

Of course if you want to know if the intersection point is on either of the vectors, then you have to find t for v2 too:

v3={vx:v1.p0.x-v2.p0.x, vy:v1.p0.y-v2.p0.y};
var t=perP(v3, v1)/perP(v2, v1);

In this example try to drag points and see where the vectors intersect:

If you are interested about actual way how the intersection algorithm is found, please look here.

You can download the source fla.

Next: Bounce.