Uncaught TypeError: THREE.PointerLockControls is not a constructor
I can't use firstperson controls for whatever reason, I am really lost for reason with this one. It's got me really stumped.
const THREE = require('THREE');
var FirstPersonControls = require('first-person-controls');
const CANNON = require('cannon');
var keyboard = new THREEx.KeyboardState();
var lights = [];
var camSpeed = 1;
var world, mass, body, body2, shape, shape2, timeStep=1/60,
camera, scene, renderer, geometry, material, mesh, textureCube;
initThree();
initCannon();
animate();
function initCannon() {
world = new CANNON.World();
world.gravity.set(0,-9.8,0);
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 10;
shape = new CANNON.Box(new CANNON.Vec3(1,1,1));
shape2 = new CANNON.Box(new CANNON.Vec3(50,1,50));
mass = 1;
body = new CANNON.Body({
mass: 1
});
body2 = new CANNON.Body({
mass: 0
});
body.position.set(1,10,1);
body.addShape(shape);
body2.addShape(shape2);
body.angularDamping = 0.5;
world.addBody(body);
world.addBody(body2);
}
function initThree() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10000 );
var controls = new THREE.FirstPersonControls(camera);
controls.lookSpeed = 0.1;
controls.movementSpeed = 10;
var clock = new THREE.Clock(true);
var prefix = ".png"
var r = __dirname + "/skyboxes/mp_cliffside/";
var urls = [
r + "px" + prefix, r + "nx" + prefix,
r + "py" + prefix, r + "ny" + prefix,
r + "pz" + prefix, r + "nz" + prefix
];
textureCube = new THREE.CubeTextureLoader().load( urls );
var dottedAlphaMap = new THREE.TextureLoader().load( __dirname + "/textures/brickmap.png" );
var dottedAlphaMap2 = new THREE.TextureLoader().load( __dirname + "/textures/stonemap-wet-texture.jpg" );
scene.background = textureCube;
lights[0] = new THREE.PointLight( '#ffffff', 3, 100 );
lights[0].position.set( 0, 5, 0 );
scene.add( lights[0] );
scene.add( camera );
renderer = new THREE.WebGLRenderer({ alpha:false });
renderer.setSize( window.innerWidth, window.innerHeight );
camera.position.y = 40;
camera.rotation.x = -90 * Math.PI / 180;
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
updatePhysics();
render();
}
var controllee = camera;
function updatePhysics() {
// Step the physics world
world.step(timeStep);
// Copy coordinates from Cannon.js to Three.js
lights[0].position.copy(camera.position)
}
function render() {
requestAnimationFrame(render);
controls.update(clock.getDelta());
if(keyboard.pressed("F")){
camera.fov += 0.1;
camera.updateProjectionMatrix();
}
if(keyboard.pressed("G")){
camera.fov -= 0.1;
camera.updateProjectionMatrix();
}
if(keyboard.pressed("space")){
controllee.translateY(camSpeed/10);
}
if(keyboard.pressed("shift")){
controllee.translateY(-camSpeed/10);
}
if(keyboard.pressed("W")){
controllee.translateZ(-camSpeed/10);
}
if(keyboard.pressed("S")){
controllee.translateZ(camSpeed/10);
}
if(keyboard.pressed("A")){
controllee.translateX(-camSpeed/10);
}
if(keyboard.pressed("D")){
controllee.translateX(camSpeed/10);
}
if(keyboard.pressed("I")){
controllee.rotateX(camSpeed/100);
}
if(keyboard.pressed("K")){
controllee.rotateX(-camSpeed/100);
}
if(keyboard.pressed("J")){
controllee.rotateY(camSpeed/100);
}
if(keyboard.pressed("L")){
controllee.rotateY(-camSpeed/100);
}
if(keyboard.pressed("U")){
controllee.rotateZ(camSpeed/100);
}
if(keyboard.pressed("O")){
controllee.rotateZ(-camSpeed/100);
}
renderer.render( scene, camera );
}
I am using imported three.js and cannon.js, from node package manager.
I am trying to get the controls to be like an fps, but stuff like this keeps getting in my way!
Any help is appreciated, the only thing i can think of is that its not included in the NPM version of three, in which case, I'm SOL
Update: I have changed my code to include three via a tag. Same goes with the PointerLockControls, but now the problem is that I dont know how the heck to lock the pointer.
UNDERSTAND that you have to use "controls.lock()" to effectively lock your mouse to the screen (your pointer will disappear and you will be able to look around like a FPS game).
Unfortunately, you CAN NOT lock the mouse pointer from code. Instead, a user interaction WITH A DOM ELEMENT is required.
The simplest Dom element you can use is the "body", by using document.body.. see:
//add document.body to PointerLockControls constructor
let fpsControls = new PointerLockControls( camera , document.body );
//add event listener to your document.body
document.body.addEventListener( 'click', function () {
//lock mouse on screen
fpsControls.lock();
}, false );
NOTE 1: no need to call fpsControls.update() in animation function;
NOTE 2: make sure your body section is IN FRONT of the canvas and covering the entire screen, setting z-index: -1 on the canvas' CSS if necessary (or setting z-index: 10, in body's CSS ). Example:
body{
z-index: 10
margin: 0;
padding: 0;
height: 100vh;
width: 100vh;
overflow: hidden;
}
This way, you can click anywhere in the screen to experience the expected behavior. ESC will make you unlock the controller
Keep Calm and Happy Coding
but now the problem is that I don't know how the heck to lock the pointer.
You can do it like in the following example:
Create splash screen that says "Click to Play"
Register an click event listener to the respective DOM element
In the listener code call document.body.requestPointerLock() in order to asynchronously ask the browser for the pointer lock
Related
I am trying to include a skybox to a scene in a web page, so I followed a tutorial I found (https://dev.to/codypearce/how-to-create-a-skybox-with-three-js-2bn8), everything seems to work correctly as my console (on firefox) doesn't display any errors or warning.
First the code creates an array of texture, then assembles the textures in a box and finally adds the box to the scene. I don't have any light in my scene as every objects are visible without any so far (and when I try to add one it doesn't change anything, and the console doesn't show any error either).
I thought it could be a matter of distance of the camera to the skybox so I got the skybox closer to the camera but still nothing.
I put my code down here if you want to see what I did so far. Thanks in advance for your help!
var camera, scene, rendu;
var r, t;
init();
function init() {
r = 3;
t = 1.1;
// ---------- scene et camera --------- //
camera = new THREE.PerspectiveCamera( 70 , window.innerWidth / window.innerHeight , 0.01 , 2000 );
camera.position.set( 0 , 0 , 4 );
camera.lookAt(new THREE.Vector3( 0, 0, 0 ));
scene = new THREE.Scene();
loadSkybox();
// ---------- rendu ------------- //
rendu = new THREE.WebGLRenderer( { antialias: true} );
rendu.setSize( window.innerWidth, window.innerHeight );
rendu.setPixelRatio(window.devicePixelRatio);
rendu.setAnimationLoop( animation );
document.body.appendChild( rendu.domElement );
}
function animation() {
rendu.render( scene, camera );
}
function createPathStrings(filename) {
const basePath = "./ulukai/";
const baseFilename = basePath + filename;
const fileType = ".png";
const sides = ["ft", "bk", "up", "dn", "rt", "lf"];
const pathStrings = sides.map(side => {
return baseFilename + "_" + side + fileType;
});
return pathStrings;
}
function createMaterialArray(filename) {
const skyboxImagepaths = createPathStrings(filename);
const materialArray = skyboxImagepaths.map(image => {
let texture = new THREE.TextureLoader().load(image);
return new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide });
});
return materialArray;
}
function loadSkybox() {
// ----------- skybox -------------- //
var skyboxImage = "corona";
skyboxGeo = new THREE.BoxGeometry(1000, 1000, 1000);
skybox = new THREE.Mesh(skyboxGeo, createMaterialArray(skyboxImage));
scene.add(skybox);
}
So I am writing a bit of stuff if Three.JS and I seem to have hit a stump with the camera. I'm attempting to attach the camera to an imported model object and it would seem that it IS attaching, however it would seem as if shadows are negated, the distance is far off from the actual field I've created. As well as some other annoying issues like Orbit controls would be inverted and non-functional. Here is my code (with certain things blocked out because I'm hotlinking script files hosted on my server...):
// This is basically everything to setup for a basic THREE.JS field to do our work in
var scene = new THREE.Scene(); // Empty Space
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000); // Perspective Camera (Args, FOV, Aspect = W/H, Min View Dist, Max View Dist)
//var controls = new THREE.OrbitControls(camera); // We will use this to look around
camera.position.set(0, 2, 5); // Note that depth into positon is mainly the opposite of where you normally want it to be.
camera.rotation.x = -0.3 // This is an attempt to rotate the angle of the camera off of an axis
var renderer = new THREE.WebGLRenderer({antialias: true}); // Our Renderer + Antialiasing
renderer.shadowMap.enabled = true; // This allows shadows to work in our 3D animation
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // This one isn't as blocky as THREE.PCFShadowMap
renderer.setClearColor("#00CCCC"); // Note: same as 0x000000
renderer.setSize(window.innerWidth, window.innerHeight); // Renderer Dimensions
document.getElementById("container").appendChild(renderer.domElement); // Add our renderer creation to our div named "container"
// Lighting (It's not necessary but it looks cool!)
var light = new THREE.PointLight("#FFFFFF", 5, 1000); // Color, intensity, range(lighting will not exceed render distance)
light.castShadow = true;
light.position.set(5, 5, 0); // This will treat the light coming from an angle!
scene.add(light);
light.shadow.mapSize.width = 512;
light.shadow.mapSize.height = 512;
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 500;
// We will make a cube here
var cubeGeo = new THREE.BoxGeometry(1, 1, 1); // This is the shape, width, height and length of our cube. Note BoxGeometry IS the current shape!
var cubeMat = new THREE.MeshStandardMaterial({color: "#FF0000"}); // Create a basic mesh with undefined color, you can also use a singular color using Basic rather than Normal, There is also Lambert and Phong. Lambert is more of a Matte material while Phong is more of a gloss or shine effect.
var cube = new THREE.Mesh(cubeGeo, cubeMat); // Create the object with defined dimensions and colors!
cube.castShadow = true; // This will allow our cube to cast a shadow outward.
cube.recieveShadow = false // This will make our cube not recieve shadows from other objects (Although it isn't needed because it's default, you show make a habit of writing it anyways as some things default to true!)
scene.add(cube); // scene.add(object) is what we will use for almost every object we create in THREE.JS
//cube.add(camera); // This is an attempt to attach the camera to the cube...
// Loader
var ship;
var loader = new THREE.GLTFLoader();
loader.load("http://ipaddress:port/files/models/raven/scene.gltf", function(gltf) {
scene.add(gltf.scene);
ship = gltf.scene;
ship.scale.multiplyScalar(0.005);
ship.rotation.y = Math.PI;
}, undefined, function(error) {
console.error(error);
});
// Lest make a floor to show the shadow!
var floorGeo = new THREE.BoxGeometry(1000, 0.1, 1000);
var floorMat = new THREE.MeshStandardMaterial({color: "#0000FF"});
var floor = new THREE.Mesh(floorGeo, floorMat);
floor.recieveShadow = true; // This will allow the shadow from the cube to portray itself unto it.
floor.position.set(0, -3, 0);
scene.add(floor);
// Now let's create an object on the floor so that we can distance ourself from our starting point.
var buildingGeo = new THREE.BoxGeometry(10, 100, 10);
var buildingMat = new THREE.MeshNormalMaterial();
var building = new THREE.Mesh(buildingGeo, buildingMat);
building.position.z = -100;
scene.add(building);
var rotation = 0;
// Controls
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
document.addEventListener("keydown", function(event) {
console.log(event.which);
});
var camAdded = false;
var render = function() {
requestAnimationFrame(render); // This grabs the browsers frame animation function.
if (rotation == 1) {
ship.rotation.x += 0.01; // rotation is treated similarly to how two dimensional objects' location is treated
ship.rotation.y += 0.01; // however it will be based on an axis point plus the width/height and subtract but keep it's indice location!
ship.rotation.z += 0.01;
}
if (keyState[87]) { // Up
ship.rotateX(0.01);
}
if (keyState[83]) { // Down
ship.rotateX(-0.01);
}
if (keyState[65]) { // Left
ship.rotateY(0.03);
}
if (keyState[68]) { // Right
ship.rotateY(-0.03);
}
if (keyState[81]) {
ship.rotateZ(0.1);
}
if (keyState[69]) {
ship.rotateZ(-0.1);
}
if (keyState[82]) { // Reset
for (var i = 0; i < 10; i++) {
if (!ship.rotation.x == 0) {
if (ship.rotation.x > 0) {
ship.rotation.x -= 0.005;
} else if (ship.rotation.x < 0){
ship.rotation.x += 0.005;
}
}
if (!ship.rotation.z == 0) {
if (ship.rotation.z > 0) {
ship.rotation.z -= 0.01;
} else if (ship.rotation.z < 0){
ship.rotation.z += 0.01;
}
}
}
}
ship.translateZ(0.2); // This will translate our ship forward in the direction it's currently facing so that it will look as if it is flyimg.
renderer.render(scene, camera); // This will render the scene after the effects have changed (rotation!)
window.addEventListener('resize', onWindowResize, false);
}
render(); // Finally, we need to loop the animation otherwise our object will not move on it's own!
function onWindowResize() {
var sceneWidth = window.innerWidth - 20;
var sceneHeight = window.innerHeight - 20;
renderer.setSize(sceneWidth, sceneHeight);
camera.aspect = sceneWidth / sceneHeight;
camera.updateProjectionMatrix();
}
<!DOCTYPE htm>
<html>
<head>
<meta charset="utf-8">
<title>Basic Three.JS</title>
</head>
<body style="background-color: #2B2B29; color: #FFFFFF; text-align: center;">
<div id="container"></div>
<script>
window.onload = function() {
document.getElementById("container").width = window.innerWidth - 20;
document.getElementById("container").height = window.innerHeight - 20;
}
</script>
<script src="http://ipaddress:port/files/scripts/three.min.js"></script>
<script src="http://ipaddress:port/files/scripts/GLTFLoader.js"></script>
<script src="http://ipaddress:port/files/scripts/OrbitControls.js"></script>
<script src="http://ipaddress:port/files/scripts/basicthree.js"></script> <!-- This is the code below -->
</body>
</html>
Nevermind, I have found a solution - shoddy as it may be...
if (typeof ship != "undefined") {
// Previous code inside of the main three.js loop...
ship.translateZ(0.2); // Move ship
camera.position.set(ship.position.x, ship.position.y, ship.position.z); // Set the camera's position to the ships position
camera.translateZ(10); // Push the camera back a bit so it's not inside the ship
camera.rotation.set(ship.rotation.x, ship.rotation.y, ship.rotation.z); // Set the rotation of the ship to be the exact same as the ship
camera.rotateX(0.3); // Tilt the camera downwards so that it's viewing over the ship
camera.rotateY(Math.PI); // Flip the camera so it's not facing the head of the ship model.
// Note: many bits of code I have are inverted due to the ship's model being backwards (or so it seems)...
}
I have a pretty easy question for you with three.js about x position translation of an imported .obj mesh.
I'm fairly new to three.js and was wandering if someone could give me some lead on what to do or solve this problem.
So... I have this mesh on (0,-200,0) and i just wanted to move it to (50,-200,0) with a smooth translation through a button back and forth to the two positions.
objLoader = new THREE.OBJLoader();
objLoader.load('models/map_real.obj', function (obj) {
var blackMat = new THREE.MeshStandardMaterial({color:0xfaf9c9});
obj.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = blackMat;
}
});
obj.castShadow = true;
obj.receiveShadow = true;
obj.position.set(0,-200,0)
obj.rotation.y = getDeg(-20);
scene.add(obj);
objWrap = obj;
});
I have in my main.js an init() which contains all the functions such as camera(), animate(), render() etc... and from the variable objWrap.position.x it logs the correct position.
I've tried to capture the click (as the snippet below shows) on my #test button and only increment the position by 0.5 - - i get this, is not in the animate loop so it cant keep add 0.5.
$('#test').click(function(){
if (objWrap.position.x <= 50) {
objWrap.position += 0.5}
});
So the final result that i want is a button that toggle back and forth a smooth animation that goes from objWrap.position.x = 0 to objWrap.position.x = 50
I hope to have been clear, feel free to ask if you need to know more, i'll respond in seconds... All the help is truly appreciate!
Just an example of how you can do it with Tween.js:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.setScalar(50);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.GridHelper(200, 100));
var box = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshBasicMaterial({
color: "aqua"
}));
scene.add(box);
btnMove.addEventListener("click", onClick, false);
var forth = true;
function onClick() {
new TWEEN.Tween(box.position)
.to(box.position.clone().setX(forth ? 50 : 0), 1000)
.onStart(function() {
btnMove.disabled = true;
})
.onComplete(function() {
btnMove.disabled = false;
forth = !forth;
})
.start();
}
render();
function render() {
requestAnimationFrame(render);
TWEEN.update();
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>
<button id="btnMove" style="position:absolute;">Move</button>
This works with ReactJS,
import TWEEN.
import {TWEEN} from "three/examples/jsm/libs/tween.module.min";
Enable drag controller and tween animation.
const { gl, camera } = useThree();
const objects = []; // objects.push(ref.current)
useEffect(() => {
const controls = new DragControls( objects, camera, gl.domElement );
controls.addEventListener( 'dragend', (e) => {
new TWEEN.Tween(e.object.position)
.to(new Vector3(x, y, z), 1000)
.easing(TWEEN.Easing.Back.InOut)
.start();
});
})
UseFrame to show the animation.
useFrame(() => {
TWEEN.update();
});
Hope to help someone.
An example of what I'm trying to achieve: https://workshop.chromeexperiments.com/examples/guiVR/#1--Basic-Usage
How could I get the Google Cardboard crosshair, (gaze)pointer, reticle, whatever you want to call it effect in three.js? I would like to make a dot, as crosshair, in the center of the screen in my scene. Like that I would like to use a raycaster to identify what I'm looking at in VR. Which way would be best to go here?
Do I fake an X and Y position of my mouse? Because I found other people have answered how to cover this by adding an event listener to the mousemove event. But this works on desktop, and I want to bring this to mobile.
Here are the main parts needed for building your own gaze cursor:
An object that serves as the indicator (cursor) for user feedback
An array of objects that you want the cursor to interact with
A loop to iterate over the array of interactive objects to test if the cursor is pointing at them
Here's an example of how this can be implemented.
Gaze cursor indicator
Using a ring here so it can be animated, as you typically want to give the user some feedback that the cursor is about to select something, instead of instantly triggering the interaction.
const cursor = new THREE.Mesh(
new THREE.RingBufferGeometry(0.1, 0.15),
new THREE.MeshBasicMaterial({ color: "white" })
);
Interactive Objects
Keep track of the objects you want to make interactive, and the actions they should execute when they are looked at.
const selectable = [];
const cube = new THREE.Mesh(
new THREE.BoxBufferGeometry(1, 1, 1),
new THREE.MeshNormalMaterial()
);
selectable.push({
object: cube,
action() {
console.log("Cube selected");
},
});
Checking Interactive Objects
Check for interactions on every frame and execute the action.
const raycaster = new THREE.Raycaster();
(function animate() {
for (let i = 0, length = selectable.length; i < length; i++) {
const camPosition = camera.position.clone();
const objectPosition = selectable[i].object.position.clone();
raycaster.set(camPosition, camera.getWorldDirection(objectPosition));
const intersects = raycaster.intersectObject(selectable[i].object);
const selected = intersects.length > 0;
// Visual feedback to inform the user they have selected an object
cursor.material.color.set(selected ? "crimson" : "white");
// Execute object action once
if (selected && !selectable[i].selected) {
selectable[i].action();
}
selectable[i].selected = selected;
}
})();
Here's a demo of this in action:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<script type="module">
import * as THREE from "https://cdn.jsdelivr.net/npm/three#0.121.1/build/three.module.js";
import { OrbitControls } from "https://cdn.jsdelivr.net/npm/three#0.121.1/examples/jsm/controls/OrbitControls.js";
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const cameraMin = 0.0001;
const aspect = window.innerWidth / window.innerHeight;
const camera = new THREE.PerspectiveCamera(75, aspect, cameraMin, 1000);
const controls = new OrbitControls(camera, renderer.domElement);
const scene = new THREE.Scene();
camera.position.z = 5;
scene.add(camera);
const cube = new THREE.Mesh(
new THREE.BoxBufferGeometry(),
new THREE.MeshNormalMaterial()
);
cube.position.x = 1;
cube.position.y = 0.5;
scene.add(cube);
const cursorSize = 1;
const cursorThickness = 1.5;
const cursorGeometry = new THREE.RingBufferGeometry(
cursorSize * cameraMin,
cursorSize * cameraMin * cursorThickness,
32,
0,
Math.PI * 0.5,
Math.PI * 2
);
const cursorMaterial = new THREE.MeshBasicMaterial({ color: "white" });
const cursor = new THREE.Mesh(cursorGeometry, cursorMaterial);
cursor.position.z = -cameraMin * 50;
camera.add(cursor);
const selectable = [
{
selected: false,
object: cube,
action() {
console.log("Cube selected");
},
}
];
const raycaster = new THREE.Raycaster();
let firstRun = true;
(function animate() {
requestAnimationFrame(animate);
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
controls.update();
if (!firstRun) {
for (let i = 0, length = selectable.length; i < length; i++) {
const camPosition = camera.position.clone();
const objectPosition = selectable[i].object.position.clone();
raycaster.set(camPosition, camera.getWorldDirection(objectPosition));
const intersects = raycaster.intersectObject(selectable[i].object);
const selected = intersects.length > 0;
cursor.material.color.set(selected ? "crimson" : "white");
if (selected && !selectable[i].selected) {
selectable[i].action();
}
selectable[i].selected = selected;
}
}
renderer.render(scene, camera);
firstRun = false;
})();
</script>
This library works like a charm - https://github.com/skezo/Reticulum
I'm trying to learn THREE.js, and I'm having trouble getting a simple skybox to show. I've tried a 100 different things, but nothing seems to work - the combination of too little documentation with a number of different releases has got me completely tied up. I'm at the end of my rope here!
I thought it might have to do with the time it takes to load the images, but I've tried putting in some "loader" code to no avail (taken out since it doesn't seem to have done much). I'm willing to believe that I just didn't do it the "right way" though - I'm having trouble finding examples that work with the current release.
<html>
<head> <title>Skybox Demo</title> <style>canvas { width: 100%; height: 100% }</style>
<body>
<script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script>
<script>
var container;
var renderer;
var cameraCube, sceneCube;
var skyboxMesh;
var cubeTarget;
var mouseX = 0;
var mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
cameraCube = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
sceneCube = new THREE.Scene();
// Load cube textures
var path = "textures/cube/";
var format = '.jpg';
var urls = [ path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format ];
var skyCubeTexture = THREE.ImageUtils.loadTextureCube(urls);
skyCubeTexture.format = THREE.RGBFormat;
// Cube shader
var shader = THREE.ShaderUtils.lib["cube"];
shader.uniforms["tCube"].texture = skyCubeTexture;
var material = new THREE.ShaderMaterial({
fragmentShader : shader.fragmentShader,
vertexShader : shader.vertexShader,
uniforms : shader.uniforms,
depthWrite : false,
side : THREE.BackSide
});
var skyboxMesh = new THREE.Mesh( new THREE.CubeGeometry(100, 100, 100), material);
sceneCube.add(skyboxMesh);
// Renderer
renderer = new THREE.WebGLRenderer( {antialias:true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.autoClear = false;
container.appendChild( renderer.domElement );
}
function animate() {
render();
requestAnimationFrame( animate );
}
function render() {
var timer = - new Date().getTime() * 0.0002;
cameraCube.position.x = 10 * Math.cos( timer );
cameraCube.position.z = 10 * Math.sin( timer );
cameraCube.lookAt({x:0, y:0, z:0});
renderer.clear();
renderer.render(sceneCube, cameraCube);
}
</script>
</body>
</html>
Be very careful about copying examples from the net.
three.js is in alpha, and many of the examples floating around the net are out-of-date.
It is always best to start with the "official" three.js examples, as they work with the current library.
You need to assign the texture correctly:
shader.uniforms["tCube"].value = skyCubeTexture;
This was a recent change.
three.js r.53