繁体   English   中英

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

[英]Bouncing Ball Game, Mouse Detect Event, JavaScript

我已经创建了一个弹跳球,该弹跳球从我指定的HTML5画布的壁上弹起。

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

我已经搜索并找到了一些有关Java鼠标事件的教程,但是我不确定如何将它们实现到我的代码= /中。

任何帮助都将是惊人的。

<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);
}

您需要通过检查球到光标的距离来检查鼠标是否悬停在球上(命中测试)。 如果距离小于球的半径,则表示鼠标在球上。

注意,您需要根据需要调整以下代码。示例:

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
}

每次更新帧时都要这样做。

您可以像这样将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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM