0

I need to make a game where a ball drops and cannot hit the floor, and you have to make it bounce again before it hits the ground, but I don't know how to make the ball jump when the mouse clicks!

How do I make a reaction to thew mouse clicking on the screen?

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;
}
zmag
  • 6,257
  • 12
  • 26
  • 33
  • Possible duplicate of [How to Call a JS function using OnClick event](https://stackoverflow.com/questions/21477717/how-to-call-a-js-function-using-onclick-event) – Max Vollmer Apr 07 '19 at 23:13

1 Answers1

0

You just have to make an event listener as follows

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
})
  • Code-only answers are discouraged. Please click on [edit] and add some words summarising how your code addresses the question. [From Review](https://stackoverflow.com/review/low-quality-posts/22687193) – Nick Apr 08 '19 at 01:48