0

指定した HTML5 Canvas の壁で跳ね返る跳ねるボールを既に作成しています。

私の目標は、ポインター (マウス) がボールの上に置かれたときに「ゲーム オーバー」画面が表示されるようにすることです。

Javascript のマウス イベントに関するいくつかのチュートリアルを既に検索して見つけましたが、それらを自分のコードに実装する方法がよくわかりません =/.

どんな助けでも素晴らしいでしょう。

<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);

var dx = 2;
var dy = 4;

function begin()
{
    gameCanvas = document.getElementById('gameCanvas');
    context = gameCanvas.getContext('2d');
    return setInterval (draw, 20);
}

begin();


function draw()
{
    context.clearRect(0,0,600,300);
    context.fillStyle = "#0000FF";
    context.beginPath();
    context.arc(x,y,80,0,Math.PI*2,true); 
    context.closePath();
    context.fill();

    if (x < 0 || x > 600) dx=-dx

    if (y < 0 || y > 300) dy=-dy;

    x += dx;
    y += dy;
}

gameCanvas.onmousemove = function (e)
{
    var gameCanvas = e.target;
    var context = gameCanvas.getContext('2d');
    var coords = RGraph.getMouseXY(e);
}

4

2 に答える 2

1

ボールからカーソルまでの距離を確認して、マウスがボールの上にあるかどうかを確認する必要があります(ヒットテスト)。距離がボールの半径よりも小さい場合は、マウスがボールの上にあることを意味します。

以下のコードをニーズに合わせて調整する必要があることに注意してください。例:

var mouse_x = 10, mouse_y = 10, ball_x = 10, ball_y = 10, ball_radius = 70, is_game_over = false

if( Math.sqrt( Math.pow( mouse_x - ball_x, 2 ) + Math.pow( mouse_x - ball_x, 2 )) < ball_radius && !is_game_over ) {
    console.log('Cursor is over the mouse, game over')
    is_game_over = true
}

フレームの更新ごとに実行します。

于 2012-11-14T20:50:41.777 に答える
1

次のように onmousemove=SetValues() を body 要素に追加できます。

<body onmousemove=SetValues()>

コードを次のように変更します。

<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);

var dx = 2;
var dy = 4;

var mouseX;
var mouseY;

function setValues(e)
{
    mouseX = e.pageX; //get mouse x
    mouseY = e.pageY; //get mouse y
}

function begin()
{
    gameCanvas = document.getElementById('gameCanvas');
    context = gameCanvas.getContext('2d');
    return setInterval (draw, 20);
}

begin();


function draw()
{
    context.clearRect(0,0,600,300);
    context.fillStyle = "#0000FF";
    context.beginPath();
    context.arc(x,y,80,0,Math.PI*2,true); 
    context.closePath();
    context.fill();

    if (x < 0 || x > 600) dx=-dx

    if (y < 0 || y > 300) dy=-dy;

    x += dx;
    y += dy;

    //check if the mouse is on the ball
    var centerX = x + 80; //center of ball
    var centerY = y; //center of ball

    if(Math.pow((mouseX - centerX), 2) + Math.pow((mouseY - centerY), 2) <= 6400){
        //do whatever to end game
    }
}
于 2012-11-14T20:59:51.847 に答える