[0..1]
交点は、式のペアで見つかったu
の置換を計算することができた範囲内にありますちょうど私が敷設していたいくつかの古代のコードからそれを外挿/書き換えた。この例では、オブジェクトを構築する(ActionScriptの1)
いくつかの機能:
function point(x, y){
return {x, y}
}
function line(x0, y0, x1, y1){
return {
start: point(x0, y0),
end: point(x1, y1)
}
}
function ray(x, y, vx, vy){
return {
start: point(x, y),
vector: point(vx, vy)
}
}
function ray2(x, y, angle){
var rad = angle * Math.PI/180;
return ray(x, y, Math.cos(rad), Math.sin(rad));
}
交差点コード:
//returns the difference vector between two points (pointB - pointA)
function delta(a, b){ return point(b.x - a.x, b.y - a.y) }
//kind of a 2D-version of the cross-product
function cp(a, b){ return a.y * b.x - a.x * b.y }
function intersection(a, b){
var d21 = a.vector || delta(a.start, a.end),
d43 = b.vector || delta(b.start, b.end),
d13 = delta(b.start, a.start),
d = cp(d43, d21);
//rays are paralell, no intersection possible
if(!d) return null;
//if(!d) return { a, b, position: null, hitsA: false, hitsB: false };
var u = cp(d13, d21)/d,
v = cp(d13, d43)/d;
return {
a, b,
//position of the intersection
position: point(
a.start.x + d21.x * v,
a.start.y + d21.y * v
),
//is position on lineA?
hitsA: v >= 0 && v <= 1,
//is position on lineB?
hitsB: u >= 0 && u <= 1,
timeTillIntersection: v,
};
}
及び例:
var a = line(0, 0, 50, 50);
var b = line(0, 50, 50, 0); //lines are crossing
console.log(intersection(a, b));
var c = line(100, 50, 150, 0); //lines are not crossing
console.log(intersection(a, c));
var d = line(100, -1000, 100, 1000); //intersection is only on d, not on a
console.log(intersection(a, d));
var e = ray(100, 50, -1, -1); //paralell to a
console.log(intersection(a, e));
復帰情報交点の周りを通過し、通過した線/光線上にある。線や光線を渡しても気にしません。
についてtimeTillIntersection
:最初の引数/線は現在の位置と動きベクトル、第二引数でそう、その後、壁やv
を表しどんなボール/弾丸/、別名timeTillIntersection
それはまでかかる時間を決定を表す場合このボールは、ボールの速度に使用されているのと同じ単位で(現在の状態で)壁と交差/ヒットします。あなたは基本的に無料でいくつかの情報を取得します。
だから、ラインは垂直にすることはできませんか? – Beta