>y=xの関係式を利用したレクチャーサイトってなくて
どういう形で傾斜と判定をしたいのかがわかりませんが(坂道を上るか下るかでしょうか?)
y=xは『直線』の式なので、
始点と終点が決まっている『線分』と衝突判定するのは
場合によっては逆に複雑になる可能性があるからではないでしょうか。
内積や外積は一見難しく思えますし、理屈も途中計算も少々難しいのですが
最終的な計算は意外と単純化されます。
簡単な例として、点が直線の左右どちらかにあるか判定するソースです。
#module
// 点(x0, y0)と線分(始点(x1, y1) 終点(x2, y2))の外積を返す
#defcfunc outerPointToLine double x0, double y0, double x1, double y1, double x2, double y2
drc = 0.0;
drc = (y2 - y1)*(x2 - x0) - (x2 - x1)*(y2 - y0); // 外積の計算
if( absf(drc) < 0.0001 ): drc = 0.0; // 誤差レベルの数値はゼロにする
return drc;
#global
// 以下サンプル(マウスが斜線の左右どちらにあるか判定)
*main
redraw 0;
color 0, 0, 0: boxf;
color 255, 255, 255: line 320, 20, 480, 240;
pos 320, 0: mes "斜線の始点";
pos 400, 240: mes "斜線の終点";
op = outerPointToLine( mousex, mousey, 320, 20, 480, 240 ); // マウス座標と斜線の外積を取得
pos 0, 0: color 255, 255, 255;
if( op > 0.0 ) {
mes "外積がプラス(斜線の右側)";
}
else:if( op == 0.0 ) {
mes "外積がゼロ(斜線上にマウスがある)";
}
else {
mes "外積がマイナス(斜線の左側)";
}
redraw 1;
await 17;
goto *main;
これは直線との判定なので、終点よりも下の方でも左右の判定をされてしまいますが
これを応用して、線分同士の交差判定をすることも出来ます。
#module
// 点(x0, y0)と線分(始点(x1, y1) 終点(x2, y2))の外積を返す
#defcfunc outerPointToLine double x0, double y0, double x1, double y1, double x2, double y2
drc = 0.0;
drc = (y2 - y1)*(x2 - x0) - (x2 - x1)*(y2 - y0); // 外積の計算
if( absf(drc) < 0.0001 ): drc = 0.0; // 誤差レベルの数値はゼロにする
return drc;
// 線分1(始点(x0, y0) 終点(x1, y1))と線分2(始点(x2, y2) 終点(x3, y3))の交差チェック
#defcfunc crossCheck double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3
drc1 = outerPointToLine( x0, y0, x2, y2, x3, y3 );
drc2 = outerPointToLine( x1, y1, x2, y2, x3, y3 );
// 線分1の始点と終点が両方線分2の片側にある場合は交差していない
if( ((drc1 > 0.0) && (drc2 > 0.0)) || ((drc1 < 0.0) && (drc2 < 0.0)) ) {
return 0;
}
else {
drc1 = outerPointToLine( x2, y2, x0, y0, x1, y1 );
drc2 = outerPointToLine( x3, y3, x0, y0, x1, y1 );
// 線分2の始点と終点が両方線分1の片側にある場合は交差していない
if( ((drc1 > 0.0) && (drc2 > 0.0)) || ((drc1 < 0.0) && (drc2 < 0.0)) ) {
return 0;
}
}
return 1; // 上記の判定に引っかからなかった場合は交差している
#global
// 以下サンプル(四角形と斜線の交差判定)
*main
redraw 0;
color 0, 0, 0: boxf;
color 255, 255, 255: line 320, 20, 480, 240;
pos 320, 0: mes "斜線の始点";
pos 400, 240: mes "斜線の終点";
boxf mousex-10, mousey-10, mousex+10, mousey+10; // 自機(仮)
// 自機の各辺と斜線の交差確認
cp1 = crossCheck( mousex-10, mousey-10, mousex+10, mousey-10, 320, 20, 480, 240 );
cp2 = crossCheck( mousex+10, mousey-10, mousex+10, mousey+10, 320, 20, 480, 240 );
cp3 = crossCheck( mousex+10, mousey+10, mousex-10, mousey+10, 320, 20, 480, 240 );
cp4 = crossCheck( mousex-10, mousey+10, mousex-10, mousey-10, 320, 20, 480, 240 );
pos 0, 0;
// 全ての辺が交差していなければ、衝突していない
if( (cp1 == 0) && (cp2 == 0) && (cp3 == 0) && (cp4 == 0) ) {
color 255, 255, 255;
mes "衝突していない";
}
else {
color 255, 0, 0;
mes "衝突している";
}
redraw 1;
await 17;
goto *main;
あきらかに解説不足な気がしますが、
このような手法はいかがでしょうか。