HOME  >   HTML5 CANVAS  >   CSS3 ANIMATION  >   How to Make Collision Detection Animation of Crossing the Road Based on Three.js
How to Make Collision Detection Animation of Crossing the Road Based on Three.js
BY Jerry13 Nov,2020
Tags:

Three.js is a WebGL third-party library written in JavaScript, which provides a lot of 3D display functions. Today I want to share with you a road crossing game animation based on Three.js, which mainly uses the collision detection function of Three.js. There are many vehicles on the road. You can use the arrow keys to control the direction of the small square. Through the road, if the block collides with a moving vehicle, the game is over.

Advertisement

How to Make Collision Detection Animation of Crossing the Road Based on Three.js
HTML Body Code
<div id="controlls">
  <div>
    <button id="forward">↑</button>
    <button id="left">←</button>
    <button id="backward">↓</button>
    <button id="right">→</button>
  </div>
</div>

<div id="end">
  <button id="retry">Retry</button>                        
Css Code
button {
  outline: none;
  cursor: pointer;
}
#counter {
  position: absolute;
  top: 20px;
  right: 20px;
}
#end {
  position: absolute;
  min-width: 100%;
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  visibility: hidden;
}
#end button {
  background-color: red;
  padding: 20px 50px 20px 50px;
  font-family: inherit;
  font-size: inherit;
}
#controlls {
  position: absolute;
  min-width: 100%;
  min-height: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
#controlls div {
  margin-bottom: 20px;
  font-size: 0;
  max-width: 180px;
}                        
Js Code
const counterDOM = document.getElementById('counter');  
const endDOM = document.getElementById('end');  

const scene = new THREE.Scene();

const distance = 500;
const camera = new THREE.OrthographicCamera( window.innerWidth/-2, window.innerWidth/2, window.innerHeight / 2, window.innerHeight / -2, 0.1, 10000 );

camera.rotation.x = 50*Math.PI/180;
camera.rotation.y = 20*Math.PI/180;
camera.rotation.z = 10*Math.PI/180;

const initialCameraPositionY = -Math.tan(camera.rotation.x)*distance;
const initialCameraPositionX = Math.tan(camera.rotation.y)*Math.sqrt(distance**2 + initialCameraPositionY**2);
camera.position.y = initialCameraPositionY;
camera.position.x = initialCameraPositionX;
camera.position.z = distance;

const zoom = 2;

const chickenSize = 15;

const positionWidth = 42;
const columns = 17;
const boardWidth = positionWidth*columns;                        

Advertisement