弹跳球游戏,鼠标检测事件,JavaScript

时间:2012-11-14 20:19:48

标签: javascript html5 javascript-events html5-canvas coordinates

我已经创造了一个弹跳球,它从我指定的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);
}

2 个答案:

答案 0 :(得分: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
}

为每个帧更新执行此操作。

答案 1 :(得分: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
    }
}