0

我已经创建了一个弹跳球,它会从我指定的 HTML5 画布的墙壁上反弹。

我的目标是当指针(鼠标)悬停在球上时出现“游戏结束”屏幕。

我已经搜索并找到了一些关于 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 回答