Reformat code

This commit is contained in:
Arne Keller 2022-01-30 12:02:00 +01:00
parent afa224ab36
commit b19f45ada3
3 changed files with 403 additions and 462 deletions

View File

@ -10,7 +10,7 @@
<body> <body>
<div id="info"> <div id="info">
Score: <div id="score">0</div><br/> Score: <span id="score">0</span><br/>
<button id="set_head">Calibrate neutral position</button> <button id="set_head">Calibrate neutral position</button>
<p id="log"></p> <p id="log"></p>
</div> </div>

364
game.js
View File

@ -34,24 +34,24 @@ void main()
} }
`; `;
const fragmentShader = ` const fragmentShader = `
#include <common> #include <common>
uniform vec3 iResolution; uniform vec3 iResolution;
uniform float iTime; uniform float iTime;
uniform sampler2D iChannel0; uniform sampler2D iChannel0;
// By Daedelus: https://www.shadertoy.com/user/Daedelus // By Daedelus: https://www.shadertoy.com/user/Daedelus
// license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. // license: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#define TIMESCALE 0.25 #define TIMESCALE 0.25
#define TILES 8 #define TILES 8
#define COLOR 0.7, 1.6, 2.8 #define COLOR 0.7, 1.6, 2.8
varying vec2 vUv; varying vec2 vUv;
varying float z; varying float z;
void mainImage( out vec4 fragColor, in vec2 fragCoord ) void mainImage( out vec4 fragColor, in vec2 fragCoord )
{ {
vec2 uv = fragCoord.xy / iResolution.xy; vec2 uv = fragCoord.xy / iResolution.xy;
uv.x *= iResolution.x / iResolution.y; uv.x *= iResolution.x / iResolution.y;
@ -64,13 +64,13 @@ void main()
p *= 1.0 - pow(min(1.0, 12.0 * dot(r, r)), 2.0); p *= 1.0 - pow(min(1.0, 12.0 * dot(r, r)), 2.0);
fragColor = vec4(COLOR, 1.0) * p; fragColor = vec4(COLOR, 1.0) * p;
} }
void main() { void main() {
mainImage(gl_FragColor, vUv * iResolution.xy); mainImage(gl_FragColor, vUv * iResolution.xy);
} }
`; `;
const vertexShader = ` const vertexShader = `
varying vec2 vUv; varying vec2 vUv;
varying float z; varying float z;
void main() { void main() {
@ -78,27 +78,27 @@ void main()
z = -position[1]; z = -position[1];
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
} }
`; `;
const diameterOfTunnel = 100; const diameterOfTunnel = 100;
var gn; var gn;
var headSet = false; var headSet = false;
var betaReference = 0.0; var betaReference = 0.0;
var leftRightMove = 0.0; var leftRightMove = 0.0;
var upDownMove = 0.0; var upDownMove = 0.0;
var speed = 5.0; var speed = 5.0;
let score = 0; let score = 0;
let removed = 0; let removed = 0;
let running = false; let running = false;
let frameCount = 0; let frameCount = 0;
function logger(text) { function logger(text) {
console.log(text);
}
} function init_gn() {
function init_gn() {
var args = { var args = {
logger: logger logger: logger
}; };
@ -107,24 +107,32 @@ void main()
gn.init(args).then(function() { gn.init(args).then(function() {
var isAvailable = gn.isAvailable(); var isAvailable = gn.isAvailable();
if(!isAvailable.deviceOrientationAvailable) { if (!isAvailable.deviceOrientationAvailable) {
console.log({message:'Device orientation is not available.'}); console.log({
message: 'Device orientation is not available.'
});
} }
if(!isAvailable.accelerationAvailable) { if (!isAvailable.accelerationAvailable) {
console.log({message:'Device acceleration is not available.'}); console.log({
message: 'Device acceleration is not available.'
});
} }
if(!isAvailable.accelerationIncludingGravityAvailable) { if (!isAvailable.accelerationIncludingGravityAvailable) {
console.log({message:'Device acceleration incl. gravity is not available.'}); console.log({
message: 'Device acceleration incl. gravity is not available.'
});
} }
if(!isAvailable.rotationRateAvailable) { if (!isAvailable.rotationRateAvailable) {
console.log({message:'Device rotation rate is not available.'}); console.log({
message: 'Device rotation rate is not available.'
});
} }
start_gn(); start_gn();
}).catch(function(e){ }).catch(function(e) {
console.error(e); console.error(e);
}); });
@ -150,17 +158,17 @@ void main()
upDownMove = 0; upDownMove = 0;
} }
}); });
} }
function stop_gn() { function stop_gn() {
gn.stop(); gn.stop();
} }
function start_gn() { function start_gn() {
gn.start(gnCallBack); gn.start(gnCallBack);
} }
function gnCallBack(data) { function gnCallBack(data) {
if (!headSet) { if (!headSet) {
betaReference = data.do.beta; betaReference = data.do.beta;
} else { } else {
@ -169,51 +177,40 @@ void main()
let upDown = data.do.beta > betaReference ? "up" : "down"; let upDown = data.do.beta > betaReference ? "up" : "down";
upDownMove = data.do.beta - betaReference; upDownMove = data.do.beta - betaReference;
} }
} }
function set_head_gn() { function set_head_gn() {
gn.setHeadDirection(); gn.setHeadDirection();
headSet = true; headSet = true;
} }
document.getElementById("set_head").addEventListener("click", () => { document.getElementById("set_head").addEventListener("click", () => {
document.getElementById("log").innerHTML += "clicked button<br>"; document.getElementById("log").innerHTML += "clicked button<br>";
set_head_gn(); set_head_gn();
}); });
init_gn(); init_gn();
import * as THREE from './three.module.js'; import * as THREE from './three.module.js';
let scene, renderer;
const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
// import { GUI } from './jsm/libs/dat.gui.module.js'; const geometrySphere = new THREE.SphereGeometry(11, 32, 32);
const materialCube = new THREE.MeshBasicMaterial();
//import { OrbitControls } from './three/examples/jsm/controls/OrbitControls.js'; const customMaterial = new THREE.ShaderMaterial({
uniforms: {
//import { EffectComposer } from './three/examples/jsm/postprocessing/EffectComposer.js'; "c": {
//import { RenderPass } from './three/examples/jsm/postprocessing/RenderPass.js'; type: "f",
//import { ShaderPass } from '/three/examples/jsm/postprocessing/ShaderPass.js'; value: 0.8
//import { LuminosityShader } from '/three/examples/jsm/shaders/LuminosityShader.js'; },
//import { SobelOperatorShader } from '/three/examples/jsm/shaders/SobelOperatorShader.js'; "p": {
type: "f",
let scene, renderer, composer; value: 2.4
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 1000 ); },
viewVector: {
let effectSobel; type: "v3",
value: camera.position
const params = { }
enable: true
};
const geometryCube = new THREE.BoxGeometry( 20, 20, 20 );
const geometrySphere = new THREE.SphereGeometry(11, 32, 32);
const geometrySphere2 = new THREE.SphereGeometry(13, 32, 32);
const materialCube = new THREE.MeshBasicMaterial();
const outlineMaterial = new THREE.MeshBasicMaterial( { color: 0x00ffff, side: THREE.BackSide } );
const customMaterial = new THREE.ShaderMaterial({
uniforms:
{
"c": { type: "f", value: 0.8 },
"p": { type: "f", value: 2.4 },
viewVector: { type: "v3", value: camera.position }
}, },
vertexShader: vertexShaderGlow, vertexShader: vertexShaderGlow,
//vertexColors: true, //vertexColors: true,
@ -221,40 +218,42 @@ void main()
side: THREE.FrontSide, side: THREE.FrontSide,
blending: THREE.AdditiveBlending, blending: THREE.AdditiveBlending,
transparent: true transparent: true
}); });
const loader = new THREE.TextureLoader(); const loader = new THREE.TextureLoader();
const texture = loader.load('/bayer.png'); const texture = loader.load('/bayer.png');
texture.minFilter = THREE.NearestFilter; texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter;
texture.wrapS = THREE.RepeatWrapping; texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping;
const uniforms = { const uniforms = {
iTime: { value: 0 }, iTime: {
iResolution: { value: new THREE.Vector3(1, 1, 1) }, value: 0
iChannel0: { value: texture }, },
}; iResolution: {
const material = new THREE.ShaderMaterial({ value: new THREE.Vector3(1, 1, 1)
},
iChannel0: {
value: texture
},
};
const material = new THREE.ShaderMaterial({
vertexShader, vertexShader,
fragmentShader, fragmentShader,
uniforms, uniforms,
}); });
const borderGeometry = new THREE.PlaneGeometry( 1, 1 ); const borderGeometry = new THREE.PlaneGeometry(1, 1);
const positions = []; const cubes = [];
const colors = []; const borders = [];
const sizes = [];
const color = new THREE.Color();
const cubes = []; init();
const borders = []; animate();
init(); document.getElementById("start").onclick = () => {
animate();
document.getElementById("start").onclick = () => {
document.getElementById("start").style.zIndex = -10; document.getElementById("start").style.zIndex = -10;
document.getElementById("start").style.visibility = "hidden";
speed = 5.0; speed = 5.0;
score = 0; score = 0;
for (let i = 0; i < cubes.length; i++) { for (let i = 0; i < cubes.length; i++) {
@ -263,104 +262,55 @@ void main()
cubes.length = 0; cubes.length = 0;
removed = 0; removed = 0;
running = true; running = true;
} }
function init() { function gameOver() {
running = false;
document.getElementById("score").innerText = document.getElementById("score").innerText + " - Game Over!";
document.getElementById("start").style.zIndex = 0;
document.getElementById("start").style.visibility = "visible";
document.getElementById("start").innerText = "Restart";
}
function init() {
// //
scene = new THREE.Scene(); scene = new THREE.Scene();
camera.position.set( 0, 10, 25 ); camera.position.set(0, 10, 25);
camera.lookAt( scene.position ); camera.lookAt(scene.position);
//const geometry = geometrySphere2; const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
//geometry.setAttribute( 'positioned', new THREE.Float32BufferAttribute( positions, 3 ) ); scene.add(ambientLight);
//geometry.setAttribute( 'glowColor', new THREE.Float32BufferAttribute( colors, 3 ) );
////geometry.setAttribute( 'size', new THREE.Float32BufferAttribute( sizes, 1 ).setUsage( THREE.DynamicDrawUsage ) );
//const particleSystem = new THREE.Mesh( geometry, customMaterial );
//scene.add(particleSystem);
// const pointLight = new THREE.PointLight(0xffffff, 0.8);
camera.add(pointLight);
scene.add(camera);
//
//const meshCube = new THREE.Mesh( geometryCube, materialCube );
//meshCube.position.z = -30;
//meshCube.position.x = 40;
//scene.add(meshCube);
//cubes.push(meshCube);
//
const ambientLight = new THREE.AmbientLight( 0xffffff, 0.7 );
scene.add( ambientLight );
const pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera.add( pointLight );
scene.add( camera );
//
renderer = new THREE.WebGLRenderer(); renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio ); renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement ); document.body.appendChild(renderer.domElement);
// postprocessing
//composer = new EffectComposer( renderer ); window.addEventListener('resize', onWindowResize);
//const renderPass = new RenderPass( scene, camera );
//composer.addPass( renderPass );
// color to grayscale conversion }
//const effectGrayScale = new ShaderPass( LuminosityShader ); function onWindowResize() {
//composer.addPass( effectGrayScale );
// you might want to use a gaussian blur filter before
// the next pass to improve the result of the Sobel operator
// Sobel operator
//effectSobel = new ShaderPass( SobelOperatorShader );
//effectSobel.uniforms[ 'resolution' ].value.x = window.innerWidth * window.devicePixelRatio;
//effectSobel.uniforms[ 'resolution' ].value.y = window.innerHeight * window.devicePixelRatio;
//composer.addPass( effectSobel );
//const controls = new OrbitControls( camera, renderer.domElement );
//controls.minDistance = 10;
//controls.maxDistance = 100;
//
//const gui = new GUI();
//gui.add( params, 'enable' );
//gui.open();
//
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight; camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setSize(window.innerWidth, window.innerHeight);
//composer.setSize( window.innerWidth, window.innerHeight );
//effectSobel.uniforms[ 'resolution' ].value.x = window.innerWidth * window.devicePixelRatio; }
//effectSobel.uniforms[ 'resolution' ].value.y = window.innerHeight * window.devicePixelRatio;
} function animate() {
function animate() { requestAnimationFrame(animate);
requestAnimationFrame( animate );
uniforms.iTime.value = frameCount / 60.0; uniforms.iTime.value = frameCount / 60.0;
frameCount++; frameCount++;
@ -382,12 +332,9 @@ void main()
// (prevents clipping through obstacles) // (prevents clipping through obstacles)
z2 = Math.max(z1, z2 - speed); z2 = Math.max(z1, z2 - speed);
} }
let dist_squared = (x1 - x2)**2 + (y1 - y2)**2 + (z1-z2)**2; let dist_squared = (x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2;
if (dist_squared <= cubes[i].geometry.parameters.radius**2) { if (dist_squared <= cubes[i].geometry.parameters.radius ** 2) {
running = false; gameOver();
document.getElementById("score").innerText = document.getElementById("score").innerText + " - Game Over!";
document.getElementById("start").style.zIndex = 0;
document.getElementById("start").innerText = "Restart";
break; break;
} }
} }
@ -398,34 +345,26 @@ void main()
camera.position.y += 0.1 * upDownMove; camera.position.y += 0.1 * upDownMove;
if (Math.random() < 0.09) { if (Math.random() < 0.09) {
const meshCube = new THREE.Mesh( geometrySphere, materialCube ); const meshCube = new THREE.Mesh(geometrySphere, materialCube);
meshCube.position.z = camera.position.z - 930; meshCube.position.z = camera.position.z - 930;
meshCube.position.x = (2 * Math.random() - 1.0) * diameterOfTunnel; meshCube.position.x = (2 * Math.random() - 1.0) * diameterOfTunnel;
meshCube.position.y = (2 * Math.random() - 1.0) * 0.9 * diameterOfTunnel; meshCube.position.y = (2 * Math.random() - 1.0) * 0.9 * diameterOfTunnel;
const outlineMesh = new THREE.Mesh( geometrySphere, customMaterial ); const outlineMesh = new THREE.Mesh(geometrySphere, customMaterial);
outlineMesh.scale.multiplyScalar( 1.17 ); outlineMesh.scale.multiplyScalar(1.17);
outlineMesh.position.z = meshCube.position.z; outlineMesh.position.z = meshCube.position.z;
outlineMesh.position.x = meshCube.position.x; outlineMesh.position.x = meshCube.position.x;
outlineMesh.position.y = meshCube.position.y; outlineMesh.position.y = meshCube.position.y;
meshCube.add( outlineMesh ); meshCube.add(outlineMesh);
scene.add(outlineMesh); scene.add(outlineMesh);
cubes.push(outlineMesh); cubes.push(outlineMesh);
//positions.push( meshCube.position.x );
//positions.push( meshCube.position.y );
//positions.push( meshCube.position.z );
//
//color.setHSL( Math.random(), 1.0, 0.5 );
//colors.push( color.r, color.g, color.b );
//sizes.push( 20 );
scene.add(meshCube); scene.add(meshCube);
cubes.push(meshCube); cubes.push(meshCube);
} }
} }
renderer.render( scene, camera ); renderer.render(scene, camera);
for (let i = 0; i < cubes.length; i++) { for (let i = 0; i < cubes.length; i++) {
@ -444,7 +383,7 @@ void main()
if (borders.length == 0 || borders[borders.length - 1].position.z - camera.position.z > -600) { if (borders.length == 0 || borders[borders.length - 1].position.z - camera.position.z > -600) {
const newZ = borders.length == 0 ? -200 : borders[borders.length - 1].position.z - diameterOfTunnel * 2; const newZ = borders.length == 0 ? -200 : borders[borders.length - 1].position.z - diameterOfTunnel * 2;
let border = new THREE.Mesh( borderGeometry, material ); let border = new THREE.Mesh(borderGeometry, material);
//border.position.x = -70; //border.position.x = -70;
border.position.y = -diameterOfTunnel; border.position.y = -diameterOfTunnel;
border.rotation.x = -Math.PI / 2; border.rotation.x = -Math.PI / 2;
@ -453,7 +392,7 @@ void main()
scene.add(border); scene.add(border);
borders.push(border); borders.push(border);
border = new THREE.Mesh( borderGeometry, material ); border = new THREE.Mesh(borderGeometry, material);
border.position.y = diameterOfTunnel; border.position.y = diameterOfTunnel;
border.rotation.x = Math.PI / 2; border.rotation.x = Math.PI / 2;
border.position.z = newZ; border.position.z = newZ;
@ -461,7 +400,7 @@ void main()
scene.add(border); scene.add(border);
borders.push(border); borders.push(border);
border = new THREE.Mesh( borderGeometry, material ); border = new THREE.Mesh(borderGeometry, material);
border.position.x = -diameterOfTunnel; border.position.x = -diameterOfTunnel;
border.rotation.y = Math.PI / 2; border.rotation.y = Math.PI / 2;
border.position.z = newZ; border.position.z = newZ;
@ -469,7 +408,7 @@ void main()
scene.add(border); scene.add(border);
borders.push(border); borders.push(border);
border = new THREE.Mesh( borderGeometry, material ); border = new THREE.Mesh(borderGeometry, material);
border.position.x = diameterOfTunnel; border.position.x = diameterOfTunnel;
border.rotation.y = -Math.PI / 2; border.rotation.y = -Math.PI / 2;
border.position.z = newZ; border.position.z = newZ;
@ -477,8 +416,6 @@ void main()
scene.add(border); scene.add(border);
borders.push(border); borders.push(border);
} }
//console.log(borders[borders.length - 1].position.z - camera.position.z);
//console.log(borders[borders.length - 1] - camera.position.z);
for (let i = 0; i < borders.length; i++) { for (let i = 0; i < borders.length; i++) {
if (borders[i].position.z > camera.position.z + diameterOfTunnel + 50) { if (borders[i].position.z > camera.position.z + diameterOfTunnel + 50) {
scene.remove(borders[i]); scene.remove(borders[i]);
@ -486,5 +423,4 @@ void main()
i--; i--;
} }
} }
} }

View File

@ -1,11 +1,16 @@
body { body {
margin: 0; margin: 0;
background-color: #000; background-color: #000;
color: #fff;
font-family: Monospace; font-family: Monospace;
font-size: 13px;
line-height: 24px;
overscroll-behavior: none; overscroll-behavior: none;
font-size: xxx-large;
color: #fff;
text-shadow:
0.07em 0 black,
0 0.07em black,
-0.07em 0 black,
0 -0.07em black;
} }
#start { #start {
width: 50vw; width: 50vw;