Kids

Can

JavaScript

<-----Back        Next --->

Collisions on the Canvas


Play the Single tennis game to see some Collisions between shapes.

example1:

Intersecting Shapes

In games we often want to know if our objects have collisions.
In the single tennis game we need to know if the bat touches the ball.
If the 2 objects collide, the ball will bounce in a different direction.
We created a function: intersects() that returns true, if 2 shapes do intersect.



We created a function: intersects() that returns true, if 2 shapes do intersect.

 function 
 intersects( 
 x1 , 
 y1 , 
 w1 , 
 h1 , 
 x2 , 
 y2 , 
 w2 , 
 h2 , 
 ) 
 { 


 if ( 
 x2  
 > 
 x1 + w1 
 || 
 x1  
 > 
 x2 + w2 
 ) 
 { return false; } 


 if ( 
 y2  
 > 
 y1 + h1 
 || 
 y1  
 > 
 y2 + h2 
 ) 
 { return false; } 


 return true; 
 } 

We also made an intersects function that takes only 2 parameters: Object 1 and Object 2
The objects need to have x,y,width and height properties, or it will not work(find it under the JS-Editor-Button in Tryout Panels)

 intersects( 
 object1 
 , 
 object2 
 ) 
 ; 

You can find both functionsunder the JS-Editor-Button in Tryout Panels


Try the Intersect function......... .... "TryoutPanel1"
<script> var canvas; var context; //////// RECT FUNCTION //////////////////// function rect(x,y,widthRect,heightRect) { // draws rectangle context.beginPath(); context.rect(x,y,widthRect,heightRect); context.fill(); context.stroke(); } ////////// INTERSECTS ///////////////////////// function intersects(x1, y1, w1, h1, x2, y2, w2, h2) { if (x2 > x1+w1 || x1 > x2 + w2){ return false;} // if shape2 is on the right of shape1 or visa versa: no intersection if (y2 > y1+h1 || y1 > y2+h2){ return false;} // if shape2 is south of shape1 or visa versa: no intersection return true; // if none of the above are true, there must be intersection } ////// CREATE 2 OBJECTS /////////// var RED= {x:100,y:20,width:60,height:120}; // create 2 new rectangles var BLUE= {x:170,y:40,width:60,height:40}; //.... change dimensions here //////////// DRAW /////////////////////////////// function draw(){ canvas=document.getElementById('canvas'); context=canvas.getContext('2d'); context.fillStyle='red'; rect(RED.x,RED.y,RED.width, RED.height); // draw RED rect context.fillStyle='lightBlue'; rect(BLUE.x,BLUE.y,BLUE.width,BLUE.height); // draw BLUE rect if(intersects(RED.x,RED.y,RED.width,RED.height, BLUE.x, BLUE.y, BLUE.width, BLUE.height)){ document.getElementById("result").innerHTML=" these shapes intersect: BOOM! "; } else{ document.getElementById("result").innerHTML=" no intersection: change dimensions for RED and BLUE to make them intersect "; } } ///// call DRAW setTimeout(draw,100); </script> <canvas id="canvas">cant show canvas</canvas> <p id="result" style="font-size:20;color:blue ;"> ***</p> <li>This <b>intersects </b> function takes 8 parameters (x1, y1, w1, h1, x2, y2, w2, h2) </li> <li>x1, y1, w1, h1 are the x-y-coords, width and height of <b>shape 1</b></li> <li> x2, y2, w2, h2 are the x-y-coords, width and height of <b>shape 2</b> </li>





Mouse Instersects Shape

example2:


If we want to check if the mouse touches an object on the Canvas,
we need to convert the mouseCoordinates: clientX and clientY from relative to the Window
to relative to the Canvas: X and Y.

We convert from Window to Canvas with getBoundingClientRect().

 var 
 rect 
 = 
 canvas 
 . 
 getBoundingClientRect() 
 ; 


 var  
 X 
 = 
 event 
 . 
 clientX 
 - 
 rect 
 . 
 left 
 ; 


 var 
 Y 
 = 
 event 
 . 
 clientY 
 - 
 rect 
 . 
 top 
 ; 

getBoundingClientRect() creates an imaginary Rectangle Object around the Canvas. We use its dimensions.


Then we can check if the Mouse X and Y intersect the shape:

 function 
 mouseIntersect( 
 X, 
 Y 
 shape 
 ) 
 { 


 if ( 
 X 
 < 
 shape 
 .x 
 || 
 X 
 > 
 shape 
 . x + 
 shape 
 .width 
 ) 
 { return false; } 


 if ( 
 Y 
 < 
 shape 
 .y 
 || 
 Y 
 > 
 shape 
 . y + 
 shape 
 .height 
 ) 
 { return false; } 


 return true; 
 } 



Write an intersects function for Mouse......... .... "TryoutPanel2"
<script > var X; var Y; ///////////////////////////Create RECT Object///////////////////////////// var myRect= {x:50,y:20,width:100,height:40}; // create rectangle object //////////////// MOUSE INTERSECTS ///////////////////////////////// function mouseIntersects(event,obj){ // checks if mouse position is within shape var rect=document.getElementById("canvas").getBoundingClientRect(); //rect around canvas X= event.clientX - rect.left; //converts X-mouse coord to relative to canvas //.......convert Y-mouse coord to relative to canvas if(X<obj.x || X>obj.x+obj.width){return false;} // if mouse-X on left or right side of obj: no intersection // ........write if-statement for mouse-Y return true; // if both conditions false: INTERSECTION // obj should have x,y,width, height properties } ///////////// DRAW /////////////////////////////////////////// function draw(event){ // DRAW var canvas=document.getElementById("canvas"); var context= canvas.getContext('2d'); context.beginPath(); context.rect(myRect.x,myRect.y,myRect.width,myRect.height); // make rectangle path context.stroke(); // and stroke it if(event){ // check if their is a mouse event if(mouseIntersects(event,myRect)){ // if mouse is within object fill black context.fill(); } else if(!mouseIntersects(event,myRect)){ // if mouse outside object wipe + just outline context.clearRect(myRect.x,myRect.y,myRect.width,myRect.height); context.stroke(); } } document.getElementById("p").innerHTML="X="+X+" --- Y="+Y+ "----myRect=("+myRect.x+","+myRect.y+","+myRect.width+","+myRect.height+")"; } ///////////////// START ////////////////////////////// setTimeout(draw,50); </script> <p id="p">move mouse over rectangle</p> <canvas id="canvas" style="border:red solid 1" width="500" height="150" onmousemove="draw(event)"></canvas> <p>Finish the mouseIntersects() function first</p> <ul><li>convert the mouse-Y coord to <b>relative to the canvas</b>(17)</li> <li>write <b>if-statement</b> to check if mouse-Y coord is outside shape(20)</li></ul>





Make a Tennis Game
Make a Tennis Game ......... .... "TryoutPanel3"
<script> var canvas; var context; var gameover=false; var score=0; // keep score var ball=new Ball(65,65,25); var bat=new Bat(350,100,10,50); //..............add another bat for player 2 ///////////////////////RECT /////////////////////////////////// function rect(x,y,widthRect,heightRect) { // creates rectangle context.beginPath(); context.rect(x,y,widthRect,heightRect); context.fill(); context.stroke(); } //////////////////// CIRCLE /////////////////////////////////// function circle(x,y,radius) { // creates circle context.beginPath(); context.arc(x, y, radius,0, Math.PI*2, true); context.fill(); context.stroke(); } /////////////////BAT CONSTRUCTOR////////////////// function Bat(x,y,width,height) { //function creates Ball Object: x,y are midpoint of ball this.x=x; this.y=y; // bats properties this.width=width; this.height=height; //*******************THIS DRAW **********************// this.draw=function(){ context.fillStyle='green'; rect(this.x,this.y,this.width,this.height); }; } //////////////////////BALL CONSTRUCTOR /////////////////////////////// function Ball(x,y,radius) { //function creates Ball Object: x,y are midpoint of ball this.x=x; this.y=y; this.radius=radius; this.dx=1; this.dy=1; //*******************THIS DRAW **********************// this.draw=function(){ context.fillStyle='red'; circle(this.x,this.y,this.radius); }; //*******************THIS MOVE **********************// this.move=function(){ // makes the ball move if(!gameover){ //..........write if-statement to check if ball intersects bat: // use intersects(x1, y1, w1, h1, x2, y2, w2, h2) // then reverse direction //..........if you have 2 players, also check intersection with bat2 if(this.x-25<=0 || this.x+25>= canvas.width){ this.dx= this.dx*-1;} // checks horizontal escape //....... write if-statement to prevent ball escaping canvas vertically: reverse direction //......write code to make the ball move horizontally this.y= this.y+(this.dy*5); draw(); // draw whole canavs setTimeout(this.move.bind(this),50); // loop } } } ///////////////// INTERSECTS /////////////////////////////////////// function intersects(x1, y1, w1, h1, x2, y2, w2, h2) { if (x2 > x1+w1 || x1 > x2+w2){ return false;} if (y2 > y1+h1 || y1 > y2+h2) {return false;} return true; /* if the x-coordinate of shape1 is bigger then shape2.x + its width : shape1 must have overtaken shape2. Or Vice versa. So then the shapes don't intersect The same goes for the y-coordinates If you don't get it draw a picture of 2 shapes intersecting and not-intersecting */ } /////////////////////// MOVE BAT KEYS FUNCTION ////////////////////////////////////// function moveBat(e){ // getting the bat to move up and down var code= e.keyCode; switch(code){ case 38: // up e.preventDefault(); // otherwise window scrolls bat.y -= 30; break; case 40: // down e.preventDefault(); // otherwise window scrolls bat.y += 30; break; //..........add more keys to control bat2 } } ///////////////////// STOP //////////////////// function stop(){ gameover=true; } //////////////////////////// START /////////////////////////// function start(){ // all values back to 0. gameover=false; score=0; ball.x=65; ball.y=65; document.getElementById("score").value="score:"+score; draw(); ball.move(); canvas.focus(); } ///////////////////////// DRAW ////////////////////////////////////////////////////// function draw(){ canvas=document.getElementById('canvas'); // focus to listen to keyboard events context=canvas.getContext('2d'); context.clearRect(0,0,canvas.width,canvas.height); // wipe ball.draw() ; // draw ball bat.draw() ; // draw bat //...........draw another bat for player 2 if(score==-5||score==5){ // check if won/lost game gameover=true; } } setTimeout(start,50); </script> <p style="font-size:20;color:blue ;">This Tennis game is not finished </p> <input id="score" style="font-size:30;color:blue ; width:150px" type="text" readonly="true" value="Score=0" /> <br> <canvas id="canvas" tabindex="0" onkeydown="moveBat(event)" ondblclick="stop()" title="double click to stop" height="500" width="500" ></canvas> <button onclick="start()">start</button> <button onclick="stop()">stop</button> <p>Ball.move() function is not finished</p> <ul><li>write <b>if-statement</b> to check if ball <b>intersects</b> bat(69)</li> <li>write <b>if-statement</b> to <b>reverse direction</b> when ball escapes canvas vertically(75)</li> <li>write code to make the ball <b>move horizontally</b>(78)</li></ul> <li><b> Experts</b> Make it into a two player game(9,161,125,72) </li></ul>

<-----Back        Next --->

This username already exists.

This username already exists.

Login or register to save your work.

User name field is empty.

Your username needs to be at least 7 characters long.

Your username can not contain any of the following characters: ",', <, > , < and whitespaces.

Please enter a correct email addresss .

This email address is not found in our database .

Your password needs to be at least 7 characters long.

login
username
password
forgot password
email
register
username
password
email