I am going to create a game in html canvas. This is an air hockey game, and I got quite a lot, though that. The game has three circles: the disk that hit, and two controllers (used to hit the disk / circle).
I have a disk that bounces off walls and has the function to detect when a disk collides with a controller. The bit I'm struggling with is when two circles collide, the controller should remain stationary, and the disk should move in the right direction. I read a bunch of article but still can not understand.
This is where Codepen links my progress. You can see that the puck bounces off the controller, but not in the right direction. You will also see that the puck comes from the controller through which it passes. http://codepen.io/allanpope/pen/a01ddb29cbdecef58197c2e829993284?editors=001
I think that after this I am an elastic collision, but Iām not sure how it works. I found this article but could not get it to work.
http://gamedevelopment.tutsplus.com/tutorials/when-worlds-collide-simulating-circle-circle-collisions--gamedev-769
Heres is my collision detection feature. Turn to the drive yourself, and the controller [i] is the controller that the drive lands on.
this.discCollision = function() { for (var i = 0; i < controllers.length; i++) {
Update
Deconstructed a demonstration of a collision with a circle and tried to implement his collision formula. This below works for hitting the puck / disc forward and down, but for some reason will not hit the back or up.
this.discCollision = function() { for (var i = 0; i < controllers.length; i++) { // Minus the x pos of one disc from the x pos of the other disc var distanceX = self.x - controllers[i].x, // Minus the y pos of one disc from the y pos of the other disc distanceY = self.y - controllers[i].y, // Multiply each of the distances by itself // Squareroot that number, which gives you the distance between the two disc's distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY), // Added the two disc radius together addedRadius = self.radius + controllers[i].radius; // Check to see if the distance between the two circles is smaller than the added radius // If it is then we know the circles are overlapping if (distance < addedRadius) { var normalX = distanceX / distance, normalY = distanceY / distance, midpointX = (controllers[i].x + self.x) / 2, midpointY = (controllers[i].y + self.y) / 2, delta = ((controllers[i].velocityX - self.velocityX) * normalX) + ((controllers[i].velocityY - self.velocityY) * normalY), deltaX = delta*normalX, deltaY = delta*normalY; // Rebound puck self.x = midpointX + normalX * self.radius; self.y = midpointY + normalY * self.radius; self.velocityX += deltaX; self.velocityY += deltaY; // Accelerate once hit self.accelerationX = 3; self.accelerationY = 3; } } }