How to make multiple balls drop on click? - javascript

I have a ball that drops from cursor location, and redrops when the cursor is moved to another location. I am trying get a new ball to drop every time I click the mouse. I tried:
canvas.addEventListener('click', function(event) {
ball.draw();
});
But it doesn't seem to do anything. Is there some way to draw a NEW ball on click instead of just redrawing the same ball over and over again?
Here's the rest of the code:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var W = window.innerWidth,
H = window.innerHeight;
var running = false;
canvas.height = H; canvas.width = W;
var ball = {},
gravity = .5,
bounceFactor = .7;
ball = {
x: W,
y: H,
radius: 15,
color: "BLUE",
vx: 0,
vy: 1,
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
};
function clearCanvas() {
ctx.clearRect(0, 0, W, H);
}
function update() {
clearCanvas();
ball.draw();
ball.y += ball.vy;
ball.vy += gravity;
if(ball.y + ball.radius > H) {
ball.y = H - ball.radius;
ball.vy *= -bounceFactor;
}
}
canvas.addEventListener("mousemove", function(e){
ball.x = e.clientX;
ball.y = e.clientY;
ball.draw();
});
setInterval(update, 1000/60);
ball.draw();

Just rewrite the ball object so it becomes instantiate-able:
function Ball(W, H) {
this.x = W;
this.y = H;
this.radius = 15;
this.color = "blue";
this.vx = 0;
this.vy = 1;
}
Move the methods to prototypes (this will make them shareable across instances). In addition, add an update method so you can localize updates:
Ball.prototype = {
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
},
update: function() {
this.y += this.vy;
this.vy += gravity;
if(this.y + this.radius > H) {
this.y = H - this.radius;
this.vy *= -bounceFactor;
}
}
};
In the click event (consider renaming the array to plural form - it's easier to distinguish that way. In your code you're overriding the "array" (which is defined as an object) with a single ball object later):
var balls = []; // define an array to hold the balls
For the click event to use the x and y position of the mouse as start point for the ball, we first need to adjust it as it is relative to client window and not the canvas. To do this we get the absolute position of canvas and subtract it from the client coordinates:
canvas.addEventListener('click', function(event) {
var rect = this.getBoundingClientRect(), // adjust mouse position
x = event.clientX - rect.left,
y = event.clientY - rect.top;
balls.push(new Ball(x, y)); // add a new instance
});
Now in the main animation loop just iterate over the array. Every time there is a new ball it will be considered and updated - we just let the loop run until some condition is met (not shown):
function update() {
clearCanvas();
for(var i = 0, ball; ball = balls[i]; i++) {
ball.draw(); // this will draw current ball
ball.update(); // this will update its position
}
requestAnimationFrame();
}
Live example
If you put these together you will get:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = canvas.width, // simplified for demo
H = canvas.height,
gravity = .5,
bounceFactor = .7;
function Ball(x, y) {
this.x = x;
this.y = y;
this.radius = 15;
this.color = "blue";
this.vx = 0;
this.vy = 1
}
Ball.prototype = {
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
},
update: function() {
this.y += this.vy;
this.vy += gravity; // todo: limit bounce at some point or this value will be added
if (this.y + this.radius > H) {
this.y = H - this.radius;
this.vy *= -bounceFactor;
}
}
};
function clearCanvas() {
ctx.clearRect(0, 0, W, H);
}
var balls = []; // define an array to hold the balls
canvas.addEventListener('click', function(event) {
var rect = this.getBoundingClientRect(), // adjust mouse position
x = event.clientX - rect.left,
y = event.clientY - rect.top;
balls.push(new Ball(x, y)); // add a new instance
});
(function update() {
clearCanvas();
for (var i = 0, ball; ball = balls[i]; i++) {
ball.draw(); // this will draw current ball
ball.update(); // this will update its position
}
requestAnimationFrame(update);
})();
canvas {background:#aaa}
<canvas id="canvas" width=600 height=400></canvas>

Related

How to make a ball bounce again on click, even while in midair?

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

Spawning balls glitch

I created a small simulation have balls spawning when the mouse is left clicked on the canvas, then the balls start falling. The script is written in javascript:
var ctx = canvas.getContext("2d");
var vy = 0;
var a = 0.5;
var bouncing_factor = 0.9;
var balls = [];
class Ball {
constructor(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
show () {
ctx.fillStyle="red";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
}
bounce () {
var ground = canvas.height - this.r;
if(this.y > ground && Math.abs(vy) < a + 1) {
cancelAnimationFrame(draw);
}
else if (this.y < ground) {
vy += a;
this.y += vy;
}
else {
vy = -vy * bouncing_factor;
this.y = ground - 1;
}
}
}
function spawn(event) {
var r = (Math.random()*20)+10;
var b = new Ball(event.clientX, event.clientY, r);
balls.push(b);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < balls.length; i++) {
balls[i].show();
balls[i].bounce();
}
}
setInterval(draw,10);
The problem here is that if you run this script, it works fine for the first ball but when you spawn another ball; it follows the bouncing as the first one.
Any help will be highly appreciated.
I've made a few changes in your code: The speed vx and the acceleration a are now part of the ball object. The speed starts at 3 and the acceleration will decrease every time when the ball hits the ground. The ball stops bouncing when the acceleration this.a < .1
const canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var bouncing_factor = 0.9;
var balls = [];
class Ball {
constructor(x, y, r){
this.x = x;
this.y = y;
this.r = r;
this.vy = 3;
this.a = 0.5;
}
show () {
ctx.fillStyle="red";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
}
bounce () {
var ground = canvas.height - this.r;
if (this.y < ground) {
this.vy += this.a;
this.y += this.vy;
}
else {
this.vy = -this.vy * bouncing_factor;
this.y = ground - 1;
this.a *=.95;
}
if(Math.abs(this.a) < .1){this.a=0; this.vy=0}
}
}
function spawn(event) {
var r = (Math.random()*20)+10;
var b = new Ball(event.clientX, event.clientY, r);
balls.push(b);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < balls.length; i++) {
balls[i].show();
balls[i].bounce();
}
}
setInterval(draw,10);
canvas.addEventListener("click", spawn)
<canvas id="myCanvas" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

hmtl5 canvas collision with multiple objects?

So i am doing a flappy bird clone as coding exercise... and now i got to the part where i have to detect the collision bettwen the bird and the pipes.
I would to know how would you suggest be the best way of detecting the collision of the bird with the pipes, taking into account that i am pushing the pipes into an array
this are the main parts of the code
//Pipes proto that the bird most avoid
function Pipes(x1, y1, height1, width1, dx1, dy1, x2, y2, height2,
width2, dx2, dy2) {
this.x1 = x1;
this.y1 = y1;
this.height1 = height1;
this.width1 = width1;
this.dx1 = dx1;
this.dy1 = dy1;
this.x2 = x2;
this.y2 = y2;
this.height2 = height2;
this.width2 = width2;
this.dx2 = dx2;
this.dy2 = dy2;
this.draw = function () {
c.fillStyle = "green";
c.fillRect(x1, y1, height1, width1)
c.fillStyle = "green";
c.fillRect(x2, y2, height2, width2)
}
this.update = function () {
x1 += -dx1;
x2 += -dx2;
this.draw();
}
}
function Bird(x, y, dx, dy, radius, color, flap) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color;
this.draw = function () {
c.beginPath();
c.arc(x, y, radius, 0, 2 * Math.PI, false);
c.fillStyle = color;
c.fill();
};
this.update = function (){
flap = false;
x += dx
//gravity manager
var gravity = 0.4;
y += dy
dy += gravity;
//Screen collision manager
if (y + dy > innerHeight) {
y = innerHeight - radius;
}
if(radius < crashObj.x1 || radius < crashObj.x2 || radius <
crashObj.x1){
}
this.draw()
}
};
//Main GameLoop
function animate() {
c.clearRect(0, 0, innerWidth, innerHeight);
//canvas Color
c.fillStyle = "#C5D3E2";
c.fillRect(0, 0, window.innerWidth, window.innerHeight);
//Updates pipes
for (var i = 0; i < pipesArr.length; i++) {
pipesArr[i].update();
}
//draw and update bird into the screen
bird.update();
requestAnimationFrame(animate);
}
animate();
thanks in advance fo the answer!
What you are looking for is a circle-rectangle collision.
User markE has posted an in-depth answer on how to achieve it, along with a JS Fiddle demonstrating it.
Then on the update function, run through all the Pipes and check each of them for collision. For example:
for(var i = 0; i < pipesArr.length; i++){
...
if(RectCircleColliding(bird, pipe)){
die()
}
}

Collision detection of two arcs in html5 canvas

I am trying to detect if two balls are intersecting on a HTML5 canvas.
I need a function called intersect as a part of a constructor object called Ball.
This function will take one Ball object as an argument and return true if the two balls on the canvas are touching/ intersecting. and false otherwise.
I cant figure out how to pass in a new instance of a ball to the intersect function and then compare it to another ball on the canvas.
The function I'm working on the is the final function intersect at the end of the Ball Object.
Please see below for the code i have so far.
Any help would be greatly appreciated.
<!DOCTYPE html>
<hmtl>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvasOne" ></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvasOne");
// Set the canvas up for drawing in 2D.
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
function Ball(xpos,ypos,r) {
this.xpos = xpos;
this.ypos = ypos;
this.r = r;
this.move = function(addx,addy){
this.xpos = this.xpos + addx;
this.ypos = this.ypos + addy;
};
this.resize = function(setr){
this.r = setr;
};
this.draw = function(){
for (var i = 0; i < 7; i++) {
ctx.beginPath();
ctx.moveTo(ball.xpos, ball.ypos);
ctx.arc(ball.xpos, ball.ypos, ball.r, i*(2 * Math.PI / 7), (i+1)*(2 * Math.PI / 7));
ctx.lineWidth = 2;
ctx.strokeStyle = '#444';
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(ball.xpos, ball.ypos);
ctx.arc(ball.xpos,ball.ypos,ball.r-10,0,2*Math.PI);
ctx.lineWidth = 2;
ctx.strokeStyle = '#444';
ctx.stroke();
};
this.rotate = function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move registration point to the center of the canvas
ctx.translate(ball.xpos, ball.ypos);
// Rotate 1 degree
ctx.rotate(Math.PI / 180);
// Move registration point back to the top left corner of canvas
ctx.translate(-ball.xpos, -ball.ypos);
ball.draw();
ctx.restore();
};
this.contains = function(x, y){
this.x = this.x;
this.y = this.y;
if(Math.sqrt((x-ball.xpos)*(x-ball.xpos) + (y-ball.ypos)*(y-ball.ypos)) <= ball.r)
{
return true;
}else{
return false;
}
};
this.intersect = function(){
this.ball1 = this.ball1;
var distance = (ball.xpos * ball.xpos) + (ball.ypos *ball.ypos);
if(distance <= (ball.r + ball.r)*(ball.r + ball.r)){
return true;
}else{
return false;
}
};
}
var ball = new Ball(100,100,100);
ball.draw();
</script>
</body>
</html>
First off, if you aren't going to use the this keyword in your class, then why make it a class?
You can setup your intersect to take a Ball as a parameter. From here you can calculate the collision between this and the parameter Ball.
You distance function was off, as it only looked on the this object, and i fixed the this problem in your code:
var canvas = document.body.appendChild(document.createElement("canvas"));
// Set the canvas up for drawing in 2D.
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
function Ball(xpos, ypos, r) {
this.xpos = xpos;
this.ypos = ypos;
this.r = r;
this.move = function(addx, addy) {
this.xpos = this.xpos + addx;
this.ypos = this.ypos + addy;
};
this.resize = function(setr) {
this.r = setr;
};
this.draw = function() {
for (var i = 0; i < 7; i++) {
ctx.beginPath();
ctx.moveTo(this.xpos, this.ypos);
ctx.arc(this.xpos, this.ypos, this.r, i * (2 * Math.PI / 7), (i + 1) * (2 * Math.PI / 7));
ctx.lineWidth = 2;
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(this.xpos, this.ypos);
ctx.arc(this.xpos, this.ypos, this.r - 10, 0, 2 * Math.PI);
ctx.lineWidth = 2;
ctx.stroke();
};
this.rotate = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move registration point to the center of the canvas
ctx.translate(this.xpos, this.ypos);
// Rotate 1 degree
ctx.rotate(Math.PI / 180);
// Move registration point back to the top left corner of canvas
ctx.translate(-this.xpos, -this.ypos);
this.draw();
ctx.restore();
};
this.contains = function(x, y) {
this.x = this.x;
this.y = this.y;
if (Math.sqrt((x - this.xpos) * (x - this.xpos) + (y - this.ypos) * (y - this.ypos)) <= this.r) {
return true;
} else {
return false;
}
};
//put "ball" as a paremeter
//ball will be the foreign Ball to test intersection against
this.intersect = function(ball) {
var productX = this.xpos - ball.xpos;
var productY = this.ypos - ball.ypos;
var distance = Math.sqrt(productX * productX + productY * productY);
if (distance <= (this.r + ball.r)) {
return true;
} else {
return false;
}
};
}
var ball1 = new Ball(100, 100, 100);
var ball2 = new Ball(240, 140, 40);
function update(evt) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (evt !== void 0) {
ball2.xpos = evt.offsetX;
ball2.ypos = evt.offsetY;
}
//Pass the ball as an argument to the method
ctx.strokeStyle = ball1.intersect(ball2) ? "red" : '#444';
ball1.draw();
ball2.draw();
}
update();
canvas.onmousemove = update;
I cant figure out how to pass in a new instance of a ball to the
intersect function
Well to pass anything really it should have an argument.
this.intersect = function(otherball){
// then compare the two ball objects
Then...
var ball1 = new Ball(100,100,100);
var ball2 = new Ball(100,100,100);
ball1.draw();
ball2.draw();
console.log(ball1.intersect(ball2));

Ball collision not working

I'm working on a JQuery / JavaScript canvas brick break game, so I added the collision detection code if the ball hits the paddle or not, but when I ran the code, the collision detection code didn't work, I was wondering if anyone could help me? Here's the code.
JSFiddle: https://jsfiddle.net/18h7b9fd/
Main.js
$(document).ready(() => {
let fps = 60;
setInterval(init, 1000 / fps);
$(canvas).bind("mousemove", paddleControl);
})
// INIT
let init = () => {
draw(); //draw objects
animate(); //animate objects
collision(); //detect collision
}
// DRAW
let draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
paddle.draw();
ball.draw();
}
// ANIMATE
let animate = () => {
ball.animate();
}
// COLLISION
let collision = () => {
ball.collision();
}
// CONTROL
let paddleControl = (e) => {
// get mouse pos
let rect = canvas.getBoundingClientRect();
let root = document.documentElement;
let mouseX = e.pageX - rect.left - root.scrollLeft;
paddle.x = mouseX - paddle.w / 2;
}
Objects.js
class Paddle {
constructor(x, y, w, h, color) {
this.x = canvas.width / 2 - 100 / 2;
this.y = canvas.height - 60;
this.w = 100;
this.h = 10;
this.color = "#fff";
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
class Ball {
constructor(x, y, r, color, speedX, speedY) {
this.x = canvas.width / 2 - 10 / 2;
this.y = canvas.height / 2 - 10 / 2;
this.r = 10;
this.color = "#fff";
this.speedX = 6;
this.speedY = 6;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
}
animate() {
this.x += this.speedX;
this.y += this.speedY;
}
collision() {
// BALL TO PADDLE
let paddleTop = paddle.y - paddle.h;
let paddleBottom = canvas.height - paddleTop;
let paddleLeft = paddle.x;
let paddleRight = paddle.x + paddle.w;
if(this.y >= paddleTop && this.y <= paddleBottom &&
this.x >= paddleLeft && this.x <= paddleRight) {
this.speedY *= -1;
}
// BALL TO WALL
if(this.x >= canvas.width) this.speedX *= -1; //left
if(this.x <= 0) this.speedX *= -1; //right
if(this.y >= canvas.height) this.reset(); //bottom
if(this.y <= 0) this.speedY *= -1; //top
}
reset() {
this.x = canvas.width / 2 - this.r / 2;
this.y = canvas.height / 2 - this.r / 2;
this.animate();
}
}
let paddle = new Paddle(this.x, this.y, this.w, this.h, this.color);
let ball = new Ball(this.x, this.y, this.r, this.color, this.speedX, this.speedY);
console.log(paddle);
console.log(ball);
The problem is the way you are setting the paddle top and bottom. Use this instead:
let paddleTop = paddle.y;
let paddleBottom = paddleTop + paddle.h;
Currently the way you are setting the values makes it impossible for the condition to ever be true (as paddle bottom is always less than paddle top).
I have put together a fiddle here: https://jsfiddle.net/gegbqv5p/
You will also notice that I didn't use jQuery. For what you have so far, it really isn't necessary.

Categories