WebGL FPS camera movement along the local axis instead of the world axis with glMatrix.js - camera

I'm trying to make a FPS camera in WebGL.
When I move the camera from the initial position and then rotate, the camera moves along the start position instead of the new position.
The translation and rotation are made with glMatrix.js library.
I have the variables:
var rotateY = 0; // For rotating along the Y axis
var fronBackMovement = 0; // Front and back movement
var sideMovement = 0; // Movement from side to side
Keyboard events:
// Movement
if( key.w == true ){
fronBackMovement += 5;
}
if( key.a == true ){
sideMovement += 5;
}
if( key.s == true ){
fronBackMovement -= 5;
}
if( key.d == true ){
sideMovement -= 5;
}
Mouse movement:
// Rotation
if( mouse.movementX != 0 ){
rotateY += mouse.movementX; // mouse.movementX is screen movement of the cursor
}
Translation and rotation:
camera.matrix = mat4.fromTranslation( mat4.create() ,vec3.fromValues(sideMovement,0,fronBackMovement) )
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY )

The camera generally looks down the -Z axis so to move forward you just add the camera's Z axis to your position. If you don't want to move vertically then zero out the Y component and normalize. Finally multiply by your desired speed.
The camera's x-axis contains the side movement direction so you can do the same for that.
const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();
...
tempForwardDirection[0] = camera.matrix[8];
tempForwardDirection[1] = 0; // camera.matrix[9];
tempForwardDirection[2] = camera.matrix[10];
vec3.normalize(tempForwardDirection, tempForwardDirection)
tempSideDirection[0] = camera.matrix[0];
tempSideDirection[1] = camera.matrix[1];
tempSideDirection[2] = camera.matrix[2];
vec3.scaleAndAdd(
cameraPosition,
cameraPosition,
tempForwardDirection,
-fronBackMovement);
vec3.scaleAndAdd(
cameraPosition,
cameraPosition,
tempSideDirection,
sideMovement)
camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);
let rotateY = 0; // For rotating along the Y axis
let fronBackMovement = 0; // Front and back movement
let sideMovement = 0; // Movement from side to side
const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();
const camera = {
matrix: mat4.create(),
};
const mouse = {
movementX: 0,
};
const gl = document.querySelector("canvas").getContext("webgl");
const vs = `
uniform mat4 u_worldViewProjection;
uniform mat4 u_worldInverseTranspose;
attribute vec4 position;
attribute vec3 normal;
varying vec3 v_normal;
void main() {
gl_Position = u_worldViewProjection * position;
v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;
}
`;
const fs = `
precision mediump float;
varying vec3 v_normal;
uniform vec3 u_lightDir;
uniform vec4 u_color;
void main() {
vec3 norm = normalize(v_normal);
float light = dot(u_lightDir, norm) * .5 + .5;
gl_FragColor = vec4(u_color.rgb * light, u_color.a);
}
`;
const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
const bufferInfo = twgl.primitives.createCubeBufferInfo(gl, 1);
const projection = mat4.create();
const view = mat4.create();
const viewProjection = mat4.create();
const world = mat4.create();
const worldViewProjection = mat4.create();
const worldInverse = mat4.create();
const worldInverseTranspose = mat4.create();
const fov = degToRad(90);
const zNear = 0.1;
const zFar = 100;
const lightDir = vec3.normalize(vec3.create(), [1, 2, 3]);
const key = {};
let px = 0;
let py = 0;
let pz = 0;
let elev = 0;
let ang = 0;
let roll = 0;
const speed = 1;
const turnSpeed = 90;
let then = 0;
function render(now) {
now *= 0.001; // seconds;
const deltaTime = now - then;
then = now;
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.useProgram(progInfo.program);
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
mat4.perspective(projection, fov, aspect, zNear, zFar);
fronBackMovement = 0;
sideMovement = 0;
if( key.w == true ){
fronBackMovement = 5 * deltaTime;
}
if( key.a == true ){
sideMovement = -5 * deltaTime;
}
if( key.s == true ){
fronBackMovement = -5 * deltaTime;
}
if( key.d == true ){
sideMovement = 5 * deltaTime;
}
// Rotation
if( mouse.movementX != 0 ){
rotateY += mouse.movementX / 200; // mouse.movementX is screen movement of the cursor
mouse.movementX = 0;
}
tempForwardDirection[0] = camera.matrix[8];
tempForwardDirection[1] = 0; // camera.matrix[9];
tempForwardDirection[2] = camera.matrix[10];
vec3.normalize(tempForwardDirection, tempForwardDirection)
tempSideDirection[0] = camera.matrix[0];
tempSideDirection[1] = camera.matrix[1];
tempSideDirection[2] = camera.matrix[2];
vec3.scaleAndAdd(
cameraPosition,
cameraPosition,
tempForwardDirection,
-fronBackMovement);
vec3.scaleAndAdd(
cameraPosition,
cameraPosition,
tempSideDirection,
sideMovement)
camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);
mat4.invert(view, camera.matrix);
mat4.multiply(viewProjection, projection, view);
for (let z = -1; z <= 1; ++z) {
for (let y = -1; y <= 1; ++y) {
for (let x = -1; x <= 1; ++x) {
if (x === 0 && y === 0 && z === 0) {
continue;
}
mat4.identity(world);
mat4.translate(world, world, [x * 3, y * 3, z * 3]);
mat4.multiply(worldViewProjection, viewProjection, world);
mat4.invert(worldInverse, world);
mat4.transpose(worldInverseTranspose, worldInverse);
twgl.setBuffersAndAttributes(gl, progInfo, bufferInfo);
twgl.setUniforms(progInfo, {
u_worldViewProjection: worldViewProjection,
u_worldInverseTranspose: worldInverseTranspose,
u_color: [(x + 2) / 3, (y + 2) / 3, (z + 2) / 3, 1],
u_lightDir: lightDir,
});
twgl.drawBufferInfo(gl, bufferInfo);
}
}
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener('keydown', (e) => {
key[e.key] = true;
e.preventDefault();
});
window.addEventListener('keyup', (e) => {
key[e.key] = false;
e.preventDefault();
});
window.addEventListener('mousemove', (e) => {
mouse.movementX = e.movementX;
});
function degToRad(d) {
return d * Math.PI / 180;
}
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
pre { position: absolute; left: 1em; top: 0; }
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"></script>
<canvas></canvas>
<pre>
A = left
D = right
W = forward
S = down
</pre>

Related

add game over to javascript game

let canvas = document.getElementById("snake");
let context = canvas.getContext("2d"); //....
let box = 42;
let snake = [];
snake[0] ={
x: 8 * box,
y: 8 * box
}
let direction = "rechts";
let food ={
x: Math.floor(Math.random() * 15 + 1) * box,
y: Math.floor(Math.random() * 15 + 1) * box
}
function maakachtergrond(){
context.fillStyle = "#FFEAF0";
context.fillRect(0, 0, 16*box, 16*box);
}
function maakslang (){
for(i = 0; i < snake.length; i++){
context.fillStyle = "#FFFFFF";
context.fillRect(snake[i].x, snake[i].y, box, box);
}
}
function heteten (){
context.fillStyle = "#010101";
context.fillRect(food.x, food.y, box, box);
}
document.addEventListener('keydown', update);
function update(event){
if(event.keyCode == 37 && direction != 'rechts') direction = 'left';
if(event.keyCode == 38 && direction != 'down') direction = 'up';
if(event.keyCode == 39 && direction != 'left') direction = 'rechts';
if(event.keyCode == 40 && direction != 'up') direction = 'down';
}
function starthetspel(){
if(snake[0].x > 15*box && direction == "rechts") snake[0].x = 0;
if(snake[0].x < 0 && direction == 'left') snake[0].x = 16 * box;
if(snake[0].y > 15*box && direction == "down") snake[0].y = 0;
if(snake[0].y < 0 && direction == 'up') snake[0].y = 16 * box;
for(i = 1; i < snake.length; i++){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
clearInterval(jogo);
}
}
maakachtergrond();
maakslang();
heteten();
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if(direction == "rechts") snakeX += box;
if(direction == "left") snakeX -= box;
if (direction == "up") snakeY -= box;
if(direction == "down") snakeY += box;
if(snakeX != food.x || snakeY != food.y){
snake.pop();
}else{
food.x = Math.floor(Math.random() * 15 +1) * box;
food.y = Math.floor(Math.random() * 15 +1) * box;
}
let newHead ={
x: snakeX,
y: snakeY
}
snake.unshift(newHead);
}
let jogo = setInterval(starthetspel, 100);
how to add a game over if i touch the edge of the game. For now the snake just respawn on the other side of the game, but i would prefer it to make it a game over
Maybe something like
if fillStyle = "#FFEAF0"
window.alert(game over);
and allowing the snake to go outside his gamefield, but I don't know how. It's for a small asignment I got from my teacher and maybe someone can help me out.

TypeError: Cannot read property 'width' of undefined - Nuxt JS and canvas

I am trying to run a sketch on the canvas element in Nuxt JS but I am having some issues (I am completely new to Vue JS).
While I have no errors in VS Code, there is an error in the browser console:
client.js?06a0:84 TypeError: Cannot read property 'width' of undefined
at Blob.get (Blob_Point.js?a5e5:126)
at Blob.render (Blob_Point.js?a5e5:29)
below is the code for my Vue file:
<template>
<div>
<h1 class="pa-5 text-center">Blob</h1>
<canvas id="myCanvas" width="600" height="400"></canvas>
<!--<v-btn #click="drawRect">Clear</v-btn> -->
</div>
</template>
<script>
import Blob from "../assets/content/Blob_Point"
//import { Point } from "../assets/content/Blob_Point"
//import Point from "../assets/content/Blob_Point"
let oldMousePoint = { x: 0, y: 0 }
let blob = new Blob()
//let point = new Point()
let hover = false
let canvas
export default {
data() {
return {
canvas: null,
x: 0,
y: 0,
isDrawing: false,
rectWidth: 200,
//hover: false,
//oldMousePoint: { x: 0, y: 0 },
}
},
mounted() {
let canvas = document.getElementById("myCanvas")
this.canvas = canvas.getContext("2d")
},
created() {
new Blob("#C09EFF")
blob.canvas = canvas
blob.init()
blob.render()
},
methods: {
/* showCoordinates(e) {
this.x = e.offsetX
this.y = e.offsetY
},
drawLine(x1, y1, x2, y2) {
let ctx = this.vueCanvas
ctx.beginPath()
ctx.strokeStyle = "black"
ctx.lineWidth = 1
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
ctx.closePath()
},
draw(e) {
if (this.isDrawing) {
this.drawLine(this.x, this.y, e.offsetX, e.offsetY)
this.x = e.offsetX
this.y = e.offsetY
}
},
beginDrawing(e) {
this.x = e.offsetX
this.y = e.offsetY
this.isDrawing = true
},
stopDrawing(e) {
if (this.isDrawing) {
this.drawLine(this.x, this.y, e.offsetX, e.offsetY)
this.x = 0
this.y = 0
this.isDrawing = false
//windowWidth = 0,
}
}, */
resize() {
document.getElementById("myCanvas").width = window.innerWidth
document.getElementById("myCanvas").height = window.innerHeight
},
/*drawRect() {
this.vueCanvas.clearRect(0, 0, 600, 800)
//this.vueCanvas.beginPath()
//this.vueCanvas.rect(20, 20, this.rectWidth, 100)
//this.vueCanvas.stroke()
},*/
mouseMove(e) {
let pos = blob.center
let diff = { x: e.clientX - pos.x, y: e.clientY - pos.y }
let dist = Math.sqrt(diff.x * diff.x + diff.y * diff.y)
let angle = null
blob.mousePos = {
x: pos.x - e.clientX,
y: pos.y - e.clientY,
}
if (dist < blob.radius && hover === false) {
let vector = {
x: e.clientX - pos.x,
y: e.clientY - pos.y,
}
angle = Math.atan2(vector.y, vector.x)
hover = true
// blob.color = '#77FF00';
} else if (dist > blob.radius && hover === true) {
let vector = {
x: e.clientX - pos.x,
y: e.clientY - pos.y,
}
angle = Math.atan2(vector.y, vector.x)
hover = false
blob.color = null
}
if (typeof angle == "number") {
let nearestPoint = null
let distanceFromPoint = 100
blob.points.forEach((point) => {
if (Math.abs(angle - point.azimuth) < distanceFromPoint) {
// console.log(point.azimuth, angle, distanceFromPoint);
nearestPoint = point
distanceFromPoint = Math.abs(angle - point.azimuth)
}
})
if (nearestPoint) {
let strength = {
x: oldMousePoint.x - e.clientX,
y: oldMousePoint.y - e.clientY,
}
strength =
Math.sqrt(strength.x * strength.x + strength.y * strength.y) * 1
if (strength > 100) strength = 100
nearestPoint.acceleration = (strength / 100) * (hover ? -1 : 1)
}
}
oldMousePoint.x = e.clientX
oldMousePoint.y = e.clientY
},
},
}
</script>
<style scoped>
#myCanvas {
border: 1px solid grey;
}
</style>
and below is the Blob_Point JS file that I am importing:
/* eslint-disable */
// Blob Class
export default class Blob {
// setup function
constructor(color) {
//the objects setup
// 'this' is a reference to the current class
this.points = []
this._color = color
}
init() {
for (let i = 0; i < this.numPoints; i++) {
let point = new Point(this.divisional * (i + 1), this)
//point.acceleration = -1 + Math.random() * 2;
this.push(point)
}
}
render() {
let canvas = this.canvas
let ctx = this.ctx
let position = this.position
let pointsArray = this.points
let radius = this.radius
let points = this.numPoints
let divisional = this.divisional
let center = this.center
ctx.clearRect(0, 0, canvas.width, canvas.height)
pointsArray[0].solveWith(pointsArray[points - 1], pointsArray[1])
let p0 = pointsArray[points - 1].position
let p1 = pointsArray[0].position
let _p2 = p1
// this is the draw
ctx.beginPath()
ctx.moveTo(center.x, center.y)
ctx.moveTo((p0.x + p1.x) / 2, (p0.y + p1.y) / 2)
for (let i = 1; i < points; i++) {
pointsArray[i].solveWith(
pointsArray[i - 1],
pointsArray[i + 1] || pointsArray[0]
)
let p2 = pointsArray[i].position
var xc = (p1.x + p2.x) / 2
var yc = (p1.y + p2.y) / 2
ctx.quadraticCurveTo(p1.x, p1.y, xc, yc)
// ctx.lineTo(p2.x, p2.y);
//ctx.fillStyle = this.color;
// ctx.fillRect(p1.x-2.5, p1.y-2.5, 5, 5);
p1 = p2
}
var xc = (p1.x + _p2.x) / 2
var yc = (p1.y + _p2.y) / 2
ctx.quadraticCurveTo(p1.x, p1.y, xc, yc)
ctx.lineTo(_p2.x, _p2.y)
ctx.closePath()
ctx.fillStyle = this.color
ctx.fill()
ctx.strokeStyle = this.color
// ctx.stroke();
/*
ctx.fillStyle = '#000000';
if(this.mousePos) {
let angle = Math.atan2(this.mousePos.y, this.mousePos.x) + Math.PI;
}*/
//requestAnimationFrame(this.render.bind(this))
}
push(item) {
if (item instanceof Point) {
this.points.push(item)
}
}
set color(value) {
this._color = value
}
get color() {
return this._color
}
set canvas(value) {
if (
value instanceof HTMLElement &&
value.tagName.toLowerCase() === "canvas"
) {
this._canvas = canvas
this.ctx = this._canvas.getContext("2d")
}
}
get canvas() {
return this._canvas
}
set numPoints(value) {
if (value > 10) {
this._points = value
}
}
get numPoints() {
return this._points || 32
}
set radius(value) {
if (value > 0) {
this._radius = value
}
}
get radius() {
return this._radius || 300
}
set position(value) {
if (typeof value == "object" && value.x && value.y) {
this._position = value
}
}
get position() {
return this._position || { x: 0.5, y: 0.5 }
}
get divisional() {
return (Math.PI * 2) / this.numPoints
}
get center() {
return {
x: this.canvas.width * this.position.x,
y: this.canvas.height * this.position.y,
}
}
set running(value) {
this._running = value === true
}
get running() {
return this.running !== false
}
}
// Point Class
export class Point {
constructor(azimuth, parent) {
this.parent = parent
this.azimuth = Math.PI - azimuth
this._components = {
x: Math.cos(this.azimuth),
y: Math.sin(this.azimuth),
}
this.acceleration = -0.3 + Math.random() * 0.6
}
solveWith(leftPoint, rightPoint) {
this.acceleration =
(-0.3 * this.radialEffect +
(leftPoint.radialEffect - this.radialEffect) +
(rightPoint.radialEffect - this.radialEffect)) *
this.elasticity -
this.speed * this.friction
}
set acceleration(value) {
if (typeof value == "number") {
this._acceleration = value
this.speed += this._acceleration * 2
}
}
get acceleration() {
return this._acceleration || 0
}
set speed(value) {
if (typeof value == "number") {
this._speed = value
this.radialEffect += this._speed * 3
}
}
get speed() {
return this._speed || 0
}
set radialEffect(value) {
if (typeof value == "number") {
this._radialEffect = value
}
}
get radialEffect() {
return this._radialEffect || 0
}
get position() {
return {
x:
this.parent.center.x +
this.components.x * (this.parent.radius + this.radialEffect),
y:
this.parent.center.y +
this.components.y * (this.parent.radius + this.radialEffect),
}
}
get components() {
return this._components
}
set elasticity(value) {
if (typeof value === "number") {
this._elasticity = value
}
}
get elasticity() {
return this._elasticity || 0.001
}
set friction(value) {
if (typeof value === "number") {
this._friction = value
}
}
get friction() {
return this._friction || 0.0085
}
}
Any ideas on the why lines 29 and 127 of the Blob_Point.js file are throwing errors?
I attached 2 screens of the developer tools in chrome to show the errors along with the JS its pointing to.
Thanks for any help!
The main issue I can identify is here. I have added comments to the code.
Blob_Point.js
render() {
let canvas = this.canvas // this references the Blob Class (not the Vue instance) and there is no initialised property such as canvas in the class
}
To fix this main issue, you can do something like
Blob_Point.js
export default class Blob {
constructor(color, canvas) {
//the objects setup
// 'this' is a reference to the current class
this.points = []
this._color = color;
this.canvas = canvas
}
}
And then in the .vue file
.Vue
mounted() {
let canvas = document.getElementById("myCanvas");
this.canvas = canvas.getContext("2d");
blob = new Blob("#C09EFF", this.canvas); // now canvas in the Blob Class constructor will refer to the vue instance canvas
blob.canvas = canvas;
blob.init();
blob.render();
},
I have identified another issue here.
set canvas(value) {
if (
value instanceof HTMLElement &&
value.tagName.toLowerCase() === "canvas"
) {
this._canvas = canvas // there is no initialised constructor property as _canvas
this.ctx = this._canvas.getContext("2d") // there is no initialised constructor property such as _canvas
}
}
get canvas() {
return this._canvas // there is no initialised constructor property as _canvas
}

FPS-like camera movement with basic matrix transformations (WebGL)

I have a simple scene in WebGL where i store every transformation (for the camera and the models) in a single model/view matrix and i set them by rotating and moving said matrix.
What i want is, to being able to rotate the camera around and when i "move forward" to move towards where the camera is pointing.
So far, i have modified this code to this:
mat4.identity(mvMatrix);
mat4.rotateX(mvMatrix, degToRad(elev), mvMatrix);
mat4.rotateY(mvMatrix, degToRad(ang), mvMatrix);
mat4.rotateZ(mvMatrix, degToRad(-roll), mvMatrix);
mat4.translate(mvMatrix, [-px, -py, -pz], mvMatrix);
since it wasn't working as it was and it kind of works, until you do an extreme rotation (more than 90 degrees).
This is not a deal breaker for what i'm doing, but i want to know. Is this the best i can get without moving away from calculating the camera orientation like this?
WebGL cameras generally point down the -Z axis so to move in the direction the camera is facing you just add the camera's Z axis (elements 8, 9, 10) to the position of the camera multiplied by some velocity.
const m4 = twgl.m4;
const v3 = twgl.v3;
const gl = document.querySelector("canvas").getContext("webgl");
const vs = `
uniform mat4 u_worldViewProjection;
uniform mat4 u_worldInverseTranspose;
attribute vec4 position;
attribute vec3 normal;
varying vec3 v_normal;
void main() {
gl_Position = u_worldViewProjection * position;
v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;
}
`;
const fs = `
precision mediump float;
varying vec3 v_normal;
uniform vec3 u_lightDir;
uniform vec4 u_color;
void main() {
vec3 norm = normalize(v_normal);
float light = dot(u_lightDir, norm) * .5 + .5;
gl_FragColor = vec4(u_color.rgb * light, u_color.a);
}
`;
const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
const bufferInfo = twgl.primitives.createCubeBufferInfo(gl, 1);
const projection = m4.identity();
const camera = m4.identity();
const view = m4.identity();
const viewProjection = m4.identity();
const world = m4.identity();
const worldViewProjection = m4.identity();
const worldInverse = m4.identity();
const worldInverseTranspose = m4.identity();
const fov = degToRad(90);
const zNear = 0.1;
const zFar = 100;
const lightDir = v3.normalize([1, 2, 3]);
const keys = {};
let px = 0;
let py = 0;
let pz = 0;
let elev = 0;
let ang = 0;
let roll = 0;
const speed = 1;
const turnSpeed = 90;
let then = 0;
function render(now) {
now *= 0.001; // seconds;
const deltaTime = now - then;
then = now;
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.useProgram(progInfo.program);
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
m4.perspective(fov, aspect, zNear, zFar, projection);
m4.identity(camera);
m4.translate(camera, [px, py, pz], camera);
m4.rotateX(camera, degToRad(elev), camera);
m4.rotateY(camera, degToRad(-ang), camera);
m4.rotateZ(camera, degToRad(roll), camera);
m4.inverse(camera, view);
m4.multiply(projection, view, viewProjection);
for (let z = -1; z <= 1; ++z) {
for (let y = -1; y <= 1; ++y) {
for (let x = -1; x <= 1; ++x) {
if (x === 0 && y === 0 && z === 0) {
continue;
}
m4.identity(world);
m4.translate(world, [x * 3, y * 3, z * 3], world);
m4.multiply(viewProjection, world, worldViewProjection);
m4.inverse(world, worldInverse);
m4.transpose(worldInverse, worldInverseTranspose);
twgl.setBuffersAndAttributes(gl, progInfo, bufferInfo);
twgl.setUniforms(progInfo, {
u_worldViewProjection: worldViewProjection,
u_worldInverseTranspose: worldInverseTranspose,
u_color: [(x + 2) / 3, (y + 2) / 3, (z + 2) / 3, 1],
u_lightDir: lightDir,
});
twgl.drawBufferInfo(gl, bufferInfo);
}
}
}
if (keys['87'] || keys['83']) {
const direction = keys['87'] ? 1 : -1;
px -= camera[ 8] * deltaTime * speed * direction;
py -= camera[ 9] * deltaTime * speed * direction;
pz -= camera[10] * deltaTime * speed * direction;
}
if (keys['65'] || keys['68']) {
const direction = keys['65'] ? 1 : -1;
ang += deltaTime * turnSpeed * direction;
}
if (keys['81'] || keys['69']) {
const direction = keys['81'] ? 1 : -1;
roll += deltaTime * turnSpeed * direction;
}
if (keys['38'] || keys['40']) {
const direction = keys['38'] ? 1 : -1;
elev += deltaTime * turnSpeed * direction;
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener('keydown', (e) => {
keys[e.keyCode] = true;
e.preventDefault();
});
window.addEventListener('keyup', (e) => {
keys[e.keyCode] = false;
e.preventDefault();
});
function degToRad(d) {
return d * Math.PI / 180;
}
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
pre { position: absolute; left: 1em; top: 0; }
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<canvas></canvas>
<pre>
A = left
D = right
W = forward
S = down
Q = roll left
E = roll right
UP = look up
DN = look down
</pre>

Stop camera from moving through meshes using Raycaster

Following the documentation it was easy to figure it out how to click on a mesh, but preventing the camera from going though a mesh not that easy. I need some guidelines.
How can I stop the camera from moving through messes using Raycaster?
jsbin
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - interactive cubes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body style="margin:0;overflow:hidden;">
<div style="position:fixed;background:rgba(255,255,255,0.9);" onmouseout="new function(){controls=new function(){this.moveX=0;this.moveY=0;this.moveZ=0;this.rotateX=0;this.rotateY=0;};}">Move RightMove LeftMove DownMove UpMove BackMove FrontRotate RightRotate LeftRotate UpRotate Down</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script>
var container;
var camera, scene, raycaster, renderer;
var mouse = new THREE.Vector2(),INTERSECTED=[],clickedIn/*bc starts like it was clicked*/=false,controls;
var clock = new THREE.Clock();
init();
animate();
function init() {
controls = new function () {
this.moveX = 0;
this.moveY = 0;
this.moveZ = 0;
this.rotateX = 0;
this.rotateY = 0;
}
container = document.createElement('div');
document.body.appendChild(container);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 1, 1).normalize();
scene.add(light);
var geometry = new THREE.BoxBufferGeometry(20, 20, 20);
for (var i = 0; i < 50; i++) {
var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff }));
object.name = 'Index:' + i;
object.userData.foo = 'foo';
object.position.x = Math.floor(Math.random() * 201) - 100;
object.position.y = Math.floor(Math.random() * 201) - 100;
object.position.z = Math.floor(Math.random() * 201) - 100;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = Math.random() + 0.5;
object.scale.y = Math.random() + 0.5;
object.scale.z = Math.random() + 0.5;
scene.add(object);
}
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
container.addEventListener('click', function (event) {
event.preventDefault();
clickedIn = true;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
}, false);
window.addEventListener('resize', function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}, false);
}
function animate() {
requestAnimationFrame(animate);
// raycaster
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
for (var i = 0; i < INTERSECTED.length; i++) {
INTERSECTED[i].material.emissive.setHex(INTERSECTED[i].currentHex);
INTERSECTED.splice(i, 1);
}
for (var i = 0; clickedIn && i < intersects.length; i++) {
var length = INTERSECTED.push(intersects[0].object) - 1;
INTERSECTED.currentHex = INTERSECTED[length].material.emissive.getHex();
INTERSECTED[length].material.emissive.setHex(0xff0000);
}
// move
var delta = clock.getDelta(), step = 100, stepAngle = (Math.PI / 2);
if (controls.moveX == 1) camera.translateX(step * delta);
else if (controls.moveX == -1) camera.translateX(-step * delta);
if (controls.moveY == 1) camera.translateY(step * delta);
else if (controls.moveY == -1) camera.translateY(-step * delta);
if (controls.moveZ == 1) camera.translateZ(step * delta);
else if (controls.moveZ == -1) camera.translateZ(-step * delta);
if (controls.rotateX == 1) camera.rotateOnAxis(new THREE.Vector3(1, 0, 0), stepAngle * delta);
if (controls.rotateX == -1) camera.rotateOnAxis(new THREE.Vector3(1, 0, 0), -stepAngle * delta);
if (controls.rotateY == 1) camera.rotateOnAxis(new THREE.Vector3(0, 1, 0), stepAngle * delta);
if (controls.rotateY == -1) camera.rotateOnAxis(new THREE.Vector3(0, 1, 0), -stepAngle * delta);
camera.updateMatrixWorld();
// render
renderer.render(scene, camera);
}
</script>
</body>
</html>
For a First-Person Camera, I think that the right way to do that would be to use the bounding sphere of the camera and test it over each mesh of the scene, but if you really want to use a raycaster then I can think of 2 approaches :
Approach 1
In your rendering loop :
Update the position of your camera ;
For each object in your scene :
Create a ray that goes from the camera to the mesh and starts slightly before the camera;
Cast the ray. If an intersection is found and lies before the camera (1), move the camera to the intersection point.
Approach 2
In your rendering loop again :
Update the position of your camera ;
Create one ray that points towards the direction of the camera and starts slightly before the camera ;
Create another ray that points in the opposite direction of the camera and starts slightly after the camera ;
Cast the first ray. If an intersection is found and the intersection point lies before the camera (1) than move the camera to the intersection point ;
If no intersection is found, cast the second ray. If an intersection is found and the intersection point lies after the camera (2) than move the camera to the intersection point.
The first algorithm is in O(n), n being the number of objects in your scene whereas the second one is in O(1) but can be tricky with big meshes.

Having issues with moving div

I am trying to create a 300px by 300 px div box that moves with mouse. The only thing is when the visitor click on div it disappear. Any help would be greatly appreciated.
if((document.getElementById) && window.addEventListener ||
window.attachEvent){ (function(){ var hairCol = "#ff0000";
var d = document; var my = -10; var mx = -10; var r; var
vert = "";
var idx = document.getElementsByTagName('div').length;
var thehairs = "<div id='theiframe' scrolling='no'
style='position:absolute;width:53px;height:23px;overflow:hidden;border:0;opacity:"
+ opacity +";filter:alpha(opacity=" + opacity * 100+ ");'>dsdsds"; document.write(thehairs); var like =
document.getElementById("theiframe");
document.getElementsByTagName('body')[0].appendChild(like);
var pix = "px"; var domWw = (typeof window.innerWidth ==
"number"); var domSy = (typeof window.pageYOffset == "number");
if (domWw) r = window; else{ if (d.documentElement &&
typeof d.documentElement.clientWidth == "number" &&
d.documentElement.clientWidth != 0)
r = d.documentElement; else{
if (d.body && typeof d.body.clientWidth == "number")
r = d.body; } }
if(time != 0){ setTimeout(function(){
document.getElementsByTagName('body')[0].removeChild(like);
if (window.addEventListener){
document.removeEventListener("mousemove",mouse,false);
}
else if (window.attachEvent){
document.detachEvent("onmousemove",mouse);
}
}, time); }
function scrl(yx){ var y,x; if (domSy){
y = r.pageYOffset;
x = r.pageXOffset; } else{
y = r.scrollTop;
x = r.scrollLeft; } return (yx == 0) ? y:x; }
function mouse(e){ var msy = (domSy)?window.pageYOffset:0; if
(!e)
e = window.event; if (typeof e.pageY == 'number'){
my = e.pageY - 5 - msy;
mx = e.pageX - 4; } else{
my = e.clientY - 6 - msy;
mx = e.clientX - 6; } vert.top = my + scrl(0) + pix; vert.left = mx + pix; }
function ani(){ vert.top = my + scrl(0) + pix; setTimeout(ani,
300); }
function init(){ vert =
document.getElementById("theiframe").style; ani(); } if
(window.addEventListener){
window.addEventListener("load",init,false);
document.addEventListener("mousemove",mouse,false); } else if
(window.attachEvent){ window.attachEvent("onload",init);
document.attachEvent("onmousemove",mouse); }
})();
}//End.