Thursday, September 20, 2018

COLLISION DETECTION IN JAVASCRIPTS


GLSW4E BOOKS FACEBOOK  W4E INSTAGRAM W4E YOUTUBEW4E HOME
FOLLOW US

SIMPLE CODE FOR COLLISION DETECTION



The simple code below is useful for collision detection of a small number of objects, but can also work for a larger number. Feel free to modify or expand the code or share your contribution and suggestions.

This simple code is executed in p5 JavaScript editor.

//***************
Set up the canvass  
var Items =[];

function setup() {

          createCanvas(600, 400);

                  for (let i = 0; i< 100; i++ ){

                   Items[i] = new Item(random(width), random(height))

         }

}

Draw the objects

function draw(){

        background(0);

        for (let p of Items){

                 p.move();

                 p.showCollision();

                 p.makeHighlight(false);

                 for (let other of Items){

                            if (p!== other && p.intersects (other)){

                                   p.makeHighlight(true);

                             }

                   }

        }

}



Define the item class

class Item{

 constructor(x, y){

     this.x = x;

     this.y = y;

     this.r = 8;

      this.highlight = false;

 }

 intersects(other){

      let d = dist (this.x, this.y, other.x, 
    other.y);

     return (d < this.r + other.r);

 }

 makeHighlight(val){

     this.highlight=val;

 }

 move(){

       this.x+=random(-1, 1);

       this.y+=random(-1, 1);

 }

 showCollision(){

     noStroke();

     if (this.highlight){

        fill(0, 255, 255);

  }else {

     fill(255);

  }

      ellipse(this.x, this.y, this.r);

  

   }

}


Friday, September 14, 2018

ANIMATION IN JAVASCRIPT


GLSW4E BOOKS FACEBOOK  W4E INSTAGRAM W4E YOUTUBEW4E HOME
FOLLOW US

How to create simple animation in JavaScript

The simple JavaScript code below, create a beautiful line and round animation on the screen.

To learn more on how to install, setup, and prepare the environment to  writing and testing JavaScript codes, Go to this page. You can also find other  examples on that page.

Note, this program was written in P5 JavaScript editor. To learn how to write without  the P5 editor, please Go to this page.  


//Simple dot and line animation:
function setup (){
 createCanvas(600, 600);
}

function draw(){
background(0, 255, 0);

strokeWeight(3)
ellipse(100, 150, random(200), random(200));

strokeWeight(8);
line(random(width), random(height), 500, 100);
}

MORE JAVASCRIPT ARTICLES FROM GLS BELOW