Algorithm: Collision or Intersection of circles and rectangles

In this post I discussed the conditions to determine the collision between circles, non-rotated rectangles and collision between rectangle and circle.

Circle-Circle collision

Two circles collide if the distance between them is less than the sum of their radii. i.e

collision or intersection of circles
Overlapping/Intersection of circles
intersection or collison of circles
Non-overlapping circles

The distance is calculated using Pythagoras formula by taking the sum of the square of the differences of x-coordinates and y-coordinates of two circles and square rooting them.

d=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}

Now, let’s write the code-

var c1={
    x:30,
    y:25,
    r:10;
}
var c2={
    x:20,
    y:25,
    r:10;
}
var dx=c1.x-c2.x,
    dy= c1.y-c2.y,
    dist=Math.sqrt(dx*dx+dy*dy),
    rdist=c1.r+c2.r;
if(dist<=rdist){
   console.log("Collision detected!");
}

Rectangle-Rectangle Collision

Rectangles collide if there is no gap between them and here the rectangles considered must be non-rotating.

collision/intersection/overlapping of rectangles
Overlapping/Intersection of Rectangles
var r1={
    x:30,
    y:25,
    w:50,
    h:50;
}
var r2={
    x:20,
    y:25,
    w:50.
    h:30;
}
if(r1.x<r2.x+r2.w && r1.x+r1.w>r2.x &&
   r1.y<r2.y+r2.h && r1.y+r1.h>r2.y){
   console.log("Rectangles collided");
}

Rectangle-Circle Collision

We find the closest point of the rectangle from the circle’s center. If the distance of this point from the center is less than the radius, then the two shapes collide. The nearest point is found by clamping circle’s center to rectangle’s coordinates.

rect2
Overlapping/intersection of circle and rectangle
var circle={
    x:40,
    y:60,
    r:20;
}
var rect={
   x:35,
   y:50,
   w:100,
   h:50;
}
var nX=circle.x-Math.max(rect.x,Math.min(circle.x,rect.x+rect.w),
    nY=circle.y-Math.max(rect.y,Math.min(circle.y,rect.y+rect.h);
if(nX*nX+nY*nY<=circle.r*circle.r){
   console.log("Collision!");
}

Note that the rectangle here must not also be rotated.

 

JS:Random motion of particles on canvas

Here, I will discuss random motion of particles inside a canvas and bouncing off the boundary. However, I will skip the collision between particles in this post which is a bit tricky and maybe I will do another post only on that topic.

Run the codepen to see the demo with code.

 

I have created an object called Circle and given it x and y coordinates and speed(sx,sy) in both directions with radius 5. The function drawCircle() uses arc shape function to draw a circle on canvas.

Next, to move the circle we need to change it’s x and y position. We do this by adding speed to current x and y position and then update the position, more the value of speed the faster the circle will move at each frame.

Now, we need to handle some conditions when the x-coordinate of circle is less then 0 or more than canvas width. If the circle’s x position is less than or equals 0, we change the x-coordinate to it’s radius and move it in the opposite direction by multiplying speed with -1. Again if the x-coordinate is more than the canvas width, the speed is changed as before but this time the x-coordinate is updated by subtracting the radius from width of canvas. We do the similar thing for y-coordinate.

Untitled-1

The array circles[] stores position and speed of each circle. Both position and speed for any circle is random, which finally gives us the effect of particles moving randomly! The speed is a random value between 0.5 and 5.  Finally,  requestAnimationFrame runs the update() function and the canvas is cleared and drawn at each frame.

 

 

JS : Creating animation frame in canvas

Using drawImage method we can animate an object in a webpage. For that we need a sprite sheet image of the object i.e the sequence of images.

player
Fig : girl.png (collected from  http://jefframos.me/Sprite-Sheet)
<!doctype html>;
<head>
<title>Frame Animation<title>
<meta charset="utf-8">
<script src = 'frame.js'></script>
</head>
<body>
<canvas id='mycanvas' width='1000' height="500"></canvas>
</body>
</html>

window.onload = function(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'girl.png';
img.onload = function(){
setInterval(frameAnimation,100);
}
var x = 0,
    y = 0,
    frameSizeX = 100,
    frameSizeY = 200,
    numFrames = 7,
    index = 0;
var frameAnimation = function(){
if(index >= numFrames){
x = 0;
y = 0;
index = 0;
}
ctx.clearRect(350,150,frameSizeX,frameSizeY);
ctx.drawImage(img, x , y , frameSizeX , frameSizeY , 350 , 150 , frameSizeX , frameSizeY );
index++;
x += frameSizeX - 4;
}
}

Saving data using Local Storage

Ever thought of making your own To-do list web app or a game that can save user’s high score? Then Local Storage may help to make your life a little easier. Local Storage stores data in the browser and the data will remain save even if the browser is closed.

Local Storage stores data with key/value pair, that means for each data there is a corresponding key and when the key is entered, data is retrieved.

We need to know some methods to use this API-

Methods
localStorage.setItem(key,value)
localStorage.getItem(key)
localStorage.removeItem(key)
localStorage.clear
localStorage.key
localStorage.length

Let’s illustrate these methods using a simple example. Suppose we ask for user name and it can be save and delete. First we set up the HTML page-

<!DOCTYPE html>
<head>
<title>LocalStorage</title>
<meta charset="utf-8">
</head>
<body>
Enter Your Name<input type='text' id='userName'>
</form>
<button id='addName'>Save</button>
<button id='deleteName'>Delete</button>
<p id='savedName'></p>


<script src='data2.js'></script>
</body>
</html> 

We will be using localStorage API with JavaScript and I will explain the important steps.


var userName=document.getElementById('userName'),
savedName=document.getElementById('savedName');

var add_name=function(){
var name=userName.value;
localStorage.setItem('user',name);
savedName.innerHTML='Hello '+name;
}

var delete_name=function(){
savedName.innerHTML=&quot;&quot;;
localStorage.removeItem('user');
}

document.getElementById('addName').addEventListener('click',function(){
add_name();
});
document.getElementById('deleteName').addEventListener('click',function(){
delete_name();
})

window.onload=function(){
if(localStorage.length&gt;0){
var key=localStorage.key('user')
savedName.innerHTML='Hello '+localStorage.getItem(key);
}
}

On line 6, the name is saved using localStorage.setItem and the key for the name is given as ‘user’, you can use any other string or variable.

On line 12,localStorage.remove is called with the key and this removes the stored value from the localstorage’s array.

On line 23, when the browser is opened we check if there is any data previously stored using localStorage.length.This checks the number of elements in the array of localStorage. If it is 0 it won’t do anything,but if it is greater than zero, we retrieve the key using localStorage.key which gives the key name. Then finally we get the value of the corresponding key using localStorage.getItem which provides the required data.

Another method we haven’t use in our example is localStorage.clear. What it does actually is it remove all the elements saved in localStorage from the browser, so you should be careful using this one.

 

 

Books On JavaScript

Here is a list of some JavaScript books that I have gone through over the last few years and categorized them into novice and advanced read.

For Novice JS programmers-

  1. The Book of JavaScript By Dave Thau  -Lots of real application examples with elaborate explanations.
  2. Eloquent JavaScript-This book covers almost everything from basic to advance features including chapters on canvas element of HTML5 and Node.js . The book is also available free on their website.
  3. Head First JavaScript Programming -An easy book for someone who have just started JS.
  4. Beginning JavaScript by Jeremy McPeak

For those who have mastered the basic and want to stretch their skill, here goes the reading list-

  1. Data Structures and Algorithms with JavaScript 1st Edition by Michael McMillan Algorithms are important part of programming and knowing them will give you a strong foundation and make you a better programmer.
  2. JavaScript Definitive Guide-This is not an easy book to read and I haven’t myself finished it yet, but it teaches you the right coding style and advanced features.
  3. Secrets of the JavaScript Ninja-A great one for learning Object-oriented programming in JavaScript.