【问题标题】:Bouncing ball javascript弹跳球javascript
【发布时间】:2018-11-29 08:22:09
【问题描述】:

所以我有一个 html 页面,其中包含用于弹跳球的按钮,我想在页面加载时从中间开始球,这就是它的作用。然后我希望它在我按下名为反弹的按钮时反弹,当我点击它时它只移动 1 帧。我希望它继续弹跳。

html代码

 <button type="button" onclick="bounce()">Bounce</button>

点击按钮时球的javascript函数

var canvas;
var ctx;
var ballX = 250;
var ballY = 250;
var xVelocity = 2;
var yVelocity = 3;
var ballWidth = 50;

 //Gets Canvas + Sets Framerate
 window.onload = function() {
  canvas = document.getElementById("test");
 ctx = canvas.getContext("2d");
 setInterval(draw,1000/60);
}

//Draw EVERYTHING
function draw() {

//Color The Canvas white
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);

//Draw The Ball
ctx.beginPath();
ctx.fillStyle = color;
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.arc(ballX,ballY,ballWidth,0,Math.PI*2, true);
ctx.fill();
ctx.stroke();
ctx.closePath();

}

//Change Ball Position
function bounce()
{

 ballX += xVelocity;
 ballY += yVelocity;

 if(ballX - ballWidth <= 0) {
  xVelocity = -xVelocity;

}

//Bounce Ball Off Right 
if(ballX + ballWidth >= canvas.width) {
xVelocity = -xVelocity;

}

 //Bounce Ball Off Top
if(ballY - ballWidth <= 0) {
 yVelocity = -yVelocity;

}

//Bounce Ball Off Bottom 
if(ballY + ballWidth >= canvas.height) {
  yVelocity = -yVelocity;

}

}

【问题讨论】:

  • 您的bounce() 是移动球的动力。调用它一次将使球移动几个像素。听起来您希望球在单击按钮时开始移动?在这种情况下,您需要 a) 将初始速度设置为零 b) bounce() 球每帧,如 draw() c) 当您单击按钮时将速度设置为非零:jsfiddle.net/khrismuc/w2km0x47

标签: javascript html


【解决方案1】:

你的问题是因为你需要在 draw 函数中运行反弹,你需要一个标志来激活这个函数。

<button type="button" onclick="bounceFlag= true;">Bounce</button>

var bounceFlag = false;

在画中

if(bounceFlag) {
    bounce()
}

您可以在此处查看您的示例 [https://codepen.io/anon/pen/jQeRxM?editors=1010][

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多