Collision Implementation

share link

by Abdul Rawoof A R dot icon Updated: Mar 2, 2023

technology logo
technology logo

Guide Kit Guide Kit  

In JavaScript, collision is the overlap of elements that can be called collision detection. This is a standard part of most games when moving page elements to detect the position and then calculate if they overlap. 


To find the collision between the two objects in JavaScript, we can detect those collisions by using bounding boxes of objects, and those bounding boxes are of type THREE. Box3 and have useful methods such as isIntersectionBox, containBox, or constainsPoint, which will suit all our needs and requirements when we want to detect collisions. To check for collisions, if both the horizontal and vertical edges overlap, then we have a collision. We check when the right side of the first object is higher than the left side of the second object, and when the second object's right side is higher than the first object's left side, then it is like the vertical axis. We have two forms of collision detection in JavaScript. They are, 

  • Continuous: it is expensive and stimulates solid objects in real life. 
  • Discrete: in this, objects will end up penetrating each other. 


Here is an example of how to implement collision: 

Fig : Preview of the output that you will get on running this code from your IDE.

Code

<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<style>
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#player {
background: #000;
position: fixed;
height: 10px;
width: 10px;
left: 0px;
top: 0px;
}
#powerup {
background: blue;
position: fixed;
height: 10px;
width: 10px;
}
</style>
</head>
<!-- NOTE: Added a keyup event -->
<body onkeydown="keydown(event)" onkeyup="keyup(event)">
<div id="player"></div>
<script>
var player = document.getElementById("player");
var powerup = document.getElementById("powerup");
var object = document.getElementsByClassName("object");
var counter = 0;
var addcounter = setInterval(createObject,1);

function createObject() {
counter++;
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
newObject.style.top = Math.floor(Math.random() * (window.innerHeight - 10)) + 10 + "px";
newObject.style.left = Math.floor(Math.random() * (window.innerWidth - 10)) + 10 + "px";
document.body.appendChild(newObject);
if (counter > 10) {
clearInterval(addcounter);
}
}

setInterval(collisionDetection,1);
function collisionDetection() {
for (i = 0; i < object.length; i++) { 
// Player Right to Object Left
if (player.offsetLeft + player.offsetWidth <= object[i].offsetLeft + 1 &&
    player.offsetLeft + player.offsetWidth >= object[i].offsetLeft &&
    player.offsetTop < object[i].offsetTop + object[i].offsetHeight &&
    player.offsetHeight + player.offsetTop > object[i].offsetTop) {
player.style.left = object[i].offsetLeft - player.offsetWidth + "px";   
}
// Player Left to Object Right
if (player.offsetLeft >= object[i].offsetLeft + object[i].offsetWidth - 1 &&
    player.offsetLeft <= object[i].offsetLeft + object[i].offsetWidth &&
    player.offsetTop < object[i].offsetTop + object[i].offsetHeight &&
    player.offsetHeight + player.offsetTop > object[i].offsetTop) {
player.style.left = object[i].offsetLeft + object[i].offsetWidth + "px";   
}
// Player Bottom to Object Top
if (player.offsetLeft < object[i].offsetLeft + object[i].offsetWidth &&
    player.offsetLeft + player.offsetWidth > object[i].offsetLeft &&
    player.offsetTop + player.offsetHeight >= object[i].offsetTop &&
    player.offsetTop + player.offsetHeight <= object[i].offsetTop + 1) {
player.style.top = object[i].offsetTop - player.offsetHeight + "px";   
}
// Player Top to Object Bottom
if (player.offsetLeft < object[i].offsetLeft + object[i].offsetWidth &&
    player.offsetLeft + player.offsetWidth > object[i].offsetLeft &&
    player.offsetTop <= object[i].offsetTop + object[i].offsetHeight &&
    player.offsetTop >= object[i].offsetTop + object[i].offsetHeight - 1) {
player.style.top = object[i].offsetTop + object[i].offsetHeight + "px";   
}
}
}


// NOTE: Storing the pressed key in a variable
var key = -1;

function keyup() { key = -1; }

function keydown(event) {
key = event.keyCode;
}

// NOTE: Running the update function every frame
function update() {
if (key == 40) {
player.style.top = player.offsetTop + 1 + "px";
}
if (key == 39) {
player.style.left = player.offsetLeft + 1 + "px";
}
if (key == 38) {
player.style.top = player.offsetTop - 1 + "px";
}
if (key == 37) {
player.style.left = player.offsetLeft - 1 + "px";
}

  requestAnimationFrame(update);
}

update();
</script>
</body>
</html>

Instructions

Follow the steps carefully to get the output easily.

  1. Install Visual Studio Code IDE.
  2. Create a new html file.
  3. Copy the code snippet using 'copy' button and paste it in that html file in your IDE.
  4. Save the file and run the html file directly from the file location.


I hope you found this useful.


I found this code snippet by searching for 'implementing collision' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created and tested in Visual Studio Code 1.74.1.


Using this solution, we are able to implement collision in javascript with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to implement collision in javascript.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.