0

シーソーゲームを開発していますが、助けが必要です。

現在、HTML5 キャンバス上の 10 点の座標をランダムに生成しています。

キャンバスが 500 px x 500 px であるとしましょう - ポイントを 100 から 400 の間で生成し、キャンバスの境界線から離れた位置に集中させました。

このために、canvas の高さと幅を表すxwxhという関数randomFromInterval()を使用しています。

これらの 10 点 (それぞれキャンバス上の x 座標と y 座標を持つ) から: - 5 点が十字の中心になります - 5 点が の中心になります

ボール (ユーザーがナビゲートした) がクロスを越えるとポイントを獲得し、穴に落ちると負けます。

これが私の問題です:

数字のランダム性により、一部の座標が他の座標に近づきすぎているため、十字の上に「穴」の一部を描くことができました。

現在、乱数のペアは次のようになります: [1, 5] と [2, 6]

x = 1 と y = 5 (キャンバス上の座標) に十字を描き、 x = 2 と y = 6 に穴を描くと、この 2 つが重なります。

コードは次のとおりです。

function randomFromInterval(from,to){
    return Math.floor(Math.random()*(to-from+1)+from);
}

function crossesAndHoles(){
        var crossx, crossy, col;
        for(var i=0; i<=10; i++){
            crossPos = [];
            crossx = randomFromInterval(100, xw-100); // the xw  is the width of the canvas
            crossy = randomFromInterval(100, xh-100); // the xh is the height of the canvas
            col = checkcollision(crossx, crossy, xdim); // here I check the collision with the maze which is drew on the canvas
            if((crossx != crossy) && col == 0){
                crossPos.push(crossx);
                crossPos.push(crossy);
                crossesPos.push(crossPos);
            }
        }
    }

何か案は?

4

1 に答える 1

1

生成された新しい座標ごとに、以前に生成された座標との距離を確認できます...近すぎる場合は、新しい座標を生成します。

于 2013-08-13T16:43:30.507 に答える