Threejs - Sin Cos Test

by black strings

HTML

<div id='hide'>
  <div>To scale sine or cosine, multiply it by 1.0 or higher</div>
  <div>If you put sin and cos next to each other, at the right distance, they create a zipper effect</div>
</div>

CSS

/* fix mouse click offset errors when doing drags */
body {
  margin: 0;
}

div#hide div {
  display: none;
}

JavaScript

import * as THREE from "https://unpkg.com/[email protected]/build/three.module.js";
import { OrbitControls } from "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js";

var scene, renderer, camera;
var cube;
var controls;

var umbrellaMesh;
var objs = [];

init();
lightSetup();
animate();



function init() {
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  var width = window.innerWidth;
  var height = window.innerHeight;
  renderer.setSize(width, height);
  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();

  var gridXZ = new THREE.GridHelper(1000, 100);
  scene.add(gridXZ);

  var axes = new THREE.AxesHelper(1000);
  scene.add(axes);
  
  camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
  camera.position.y = 160;
  camera.position.z = 400;
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  controls = new OrbitControls(camera, renderer.domElement);
  

  lightSetup();
  simulate(true, 0);
  simulate(false, 60);
  
}

/**
	* param posOffset start all spheres with a position offset
	*/
function simulate(useSin = true, posOffset = 0) {
	const speed = .001;
  const lastTime = Date.now();
  const gap = 5;
  const mat = new THREE.MeshPhongMaterial({color: 0xff0000});
  const mat2 = new THREE.MeshPhongMaterial({color: 0x00ffff});
  const geo = new THREE.SphereGeometry(1, 8, 8);
  const mesh = new THREE.Mesh(geo, mat);
  const maxI = 10;
  const maxJ = 10;
  const scale = 6;
  
  for(let i=0; i<maxI; i++) {
  	for(let j=0; j<maxJ; j++) {
    	const m = mesh.clone();
      m.material = useSin ? mat : mat2;
      m.position.copy(new THREE.Vector3(i*gap, 0, j*gap));
      m.userData.origX = m.position.x;
      m.userData.callBack = () => {
      	const initialX = m.position.x;
      	const time = Date.now() - lastTime;
        // scale * sine(x) scales the wave larger
        const timeSpeedPos = (time * speed) + j;
       	const sinCos = useSin ? Math.sin(timeSpeedPos) : Math.cos(timeSpeedPos);
    ...