0

Using HTML5 canvas where would be the best place to start to move my 3 balls in random trajectories (along a smooth line, no jumping) and when they hit each other bounce away and then go on another path, until again they hit each other and again bounce away.

So far I have set up a simple example on jsfiddle where each ball follows its own path (though they do disappear off the screen).

At the moment the trajectory is as simple as

function animate(){

  // Yellow Circle
  circles[0].x+=1;
  circles[0].y+=-1.5;

  // Blue Cirlce
  circles[1].x+=-1;
  circles[1].y+=-1.5;

  // Red Circle
  circles[2].x+=1;
  circles[2].y+=-1;
  draw();

 }

I would love to see an example, but also to know what methods and calculations I should be looking at.

halfer
  • 19,824
  • 17
  • 99
  • 186
Richlewis
  • 15,070
  • 37
  • 122
  • 283
  • 1
    This is not a S.O. question. Search for tutorials on the web, rather. – GameAlchemist Jul 26 '14 at 09:00
  • As far as the random trajectories go, it seems as simple as setting your x and y components to a random float within some range, determined by yourself as preferred. Am I wrong? – David Frye Jul 26 '14 at 09:02
  • ok taking that on board i have updated the fiddle, but the behaviour of the yellow ball is too random, when the ball moves it needs to move in incremental movements – Richlewis Jul 26 '14 at 09:14

1 Answers1

5

This code is created by Adam Brookes for adambrookesprojects.co.uk on 06/10/2013.

Moving the balls

    function updateBallPos(deltaTime, ballArray) {
        for (var i = 0; i < ballArray.length; i++) {
            ballArray[i].lastGoodPosition = ballArray[i].position; // save the balls last good position.
            ballArray[i].position = ballArray[i].position.add((ballArray[i].velocity.multiply(deltaTime/10))); // add the balls (velocity * deltaTime) to position. 
        }
    }

Detecting Ball collision

function checkBallCollision(ball1, ball2) {
        var xDistance = (ball2.getX() - ball1.getX()); 
        var yDistance = (ball2.getY() - ball1.getY());
        var distanceBetween = Math.sqrt((xDistance * xDistance) + (yDistance *yDistance)); 

        var sumOfRadius = ((ball1.getRadius()) + (ball2.getRadius())); // add the balls radius together

        if (distanceBetween < sumOfRadius) {
            return true;
        }
        else {
            return false;
        }
    }

SEE DEMO HERE

All the code are clearly explained by him HERE

RELATED QUESTION HERE

halfer
  • 19,824
  • 17
  • 99
  • 186
Roshan
  • 2,144
  • 2
  • 16
  • 28