点击时需要球运动

时间:2017-04-30 00:45:40

标签: javascript canvas

我正在尝试在JavaScript中制作一个简单易玩的鸟类游戏,其目标是让用户单击一个按钮,以便将球移动通过两个矩形之间的间隙。我很难搞清楚如何让球只在点击时移动,而不是在加载页面时被调用,以及一种方法,这样每次单击“开始”按钮时,球开始从点击时的最后位置开始的路径/轨迹。我也意识到并且球后面留下了一条可以否定的线索但是如果可能的话我希望它能留下来。我稍后会考虑碰撞但是我想对这个问题有所了解,因为我对编码完全不熟悉。 非常感谢!

HTML

<canvas id="gameCanvas" width="640" height="480"></canvas>

<button id="playGame">Go!</button>

CSS

canvas { background: #eee;}

的Javascript

var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");


    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, 8, 0, Math.PI*2);
        ctx.fillStyle = "#68f442";
        ctx.fill();
        ctx.closePath();  
}

function drawSquare1(){
    ctx.beginPath();
    ctx.strokeStyle="#FF0000";
  ctx.strokeRect((canvas.width)/2, 0, 20, 200);
   ctx.closePath();
}

function drawSquare2(){
    ctx.beginPath();
    ctx.strokeStyle="#FF0000";
 ctx.strokeRect((canvas.width)/2, 280, 20, 200);
   ctx.closePath();
}

var x = canvas.width/640;
var y = canvas.height+0;
var velocityx = 1;
var velocityy = -2;
var gravity= 0.03;

function draw(){
   drawSquare1();
   drawSquare2();
   drawBall();

    velocityy += gravity; 

    x += velocityx;
    y += velocityy;
}

setInterval(draw, 1);

Here is an image of what i would like to achieve with the clicks, the picture isn't true to the actually arch of the ball in the code, but this is the general idea i am trying to achieve if one was to click at multiple instances at any point in time. Of course this would look different depending on when the clicks were being made

1 个答案:

答案 0 :(得分:0)

在你的评论中你所需要的只是一个简单的跳跃功能:

var jumpPower = 1.5;
/* ... */
function jump(){
    velocityy = -jumpPower;
}

然后你可以在画布上附加一个click事件处理程序,这样当你点击它时会触发jump函数:

canvas.addEventListener("click", jump);

或者你可以使用匿名函数一步完成这一切:

canvas.addEventListener("click", function(){
    velocityy = -jumpPower;
});

Here is a fiddle example