So I\'ve been working on a running stick man game. Unfortunately I\'ve come across this one problem I just can\'t seem to figure out. I want an alert to appear and say \"Game Ov
You can use a line intersection algorithm. Feed the two lines you want to check, if non-null result they intersect. Then determine based on which lines you fed or the position on the line in the result, which part was hit and provide action accordingly.
To optimize you could first check against a bounding box, then if bounding box is hit check each line part of the shapes.
Here is one line intersection function (source):
Line 1 is given as p0x, p0y, p1x, p1y, line 2 as p2x, p2y, p3x, p3y. If intersect an object is returned with properties x
and y
.
var intPoint = intersection( .... );
if (intPoint) {
... some action here...
}
function intersection(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
var d1x = p1x - p0x,
d1y = p1y - p0y,
d2x = p3x - p2x,
d2y = p3y - p2y,
// determinator
d = d1x * d2y - d2x * d1y,
px, py, s, t;
// continue if intersecting/is not parallel
if (d) {
px = p0x - p2x;
py = p0y - p2y;
s = (d1x * py - d1y * px) / d;
if (s >= 0 && s <= 1) {
// if s was in range, calc t
t = (d2x * py - d2y * px) / d;
if (t >= 0 && t <= 1) {
return {x: p0x + (t * d1x),
y: p0y + (t * d1y)}
}
}
}
return null
}