即使在空中,如何在单击时使球再次弹跳?

时间:2019-04-07 22:53:36

标签: javascript onclick detect bounce

我需要制作一个球掉落并且不能击中地面的游戏,并且您必须使其再次弹跳才能击中地面,但是我不知道如何在单击鼠标时使球跳起来!

我如何对鼠标在屏幕上的点击做出反应?

var canvas, ctx, container;
canvas = document.createElement('canvas');
ctx = canvas.getContext("2d");
var ball;
// Velocity y - randomly set
var vy;
var gravity = 0.5;
var bounce = 0.7;
var xFriction = 0.1;


function init() {
  setupCanvas();
  vy = (Math.random() * -15) + -5;
  ball = {
    x: canvas.width / 2,
    y: 100,
    radius: 20,
    status: 0,
    color: "red"
  };
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false);
  ctx.fillStyle = ball.color;
  ctx.fill();
  ctx.closePath()
  ballMovement();
}
setInterval(draw, 1000 / 35);

function ballMovement() {
  ball.y += vy;
  vy += gravity;
  if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
    vx *= -1;
  }

  if (ball.y + ball.radius > canvas.height) {
    ball.y = canvas.height - ball.radius;
    vy *= -bounce;

    vy = 0;

    if (Math.abs(vx) < 1.1)
      vx = 0;
    xF();
  }
}

function setupCanvas() { //setup canvas
  container = document.createElement('div');
  container.className = "container";
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  document.body.appendChild(container);
  container.appendChild(canvas);
  ctx.strokeStyle = "#ffffff";
  ctx.lineWidth = 2;
}

1 个答案:

答案 0 :(得分:0)

您只需要按如下方式制作事件监听器

window.addEventListener('click', function(event) {
    //code here
})
//but if you want it so it's just on the canvas
canvas.addEventListener('click', function(event) {
    //code here
})