STL Loader kept spinning - stl

I am using three.min.js and works beautifully but the model is spinning endlessly. How to stop it and allow user to spin manually? And the spinning is off centered also, is there away to resolve this?
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container, stats;
var camera, cameraTarget, scene, renderer;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 15);
camera.position.set(3, 0.15, 3);
cameraTarget = new THREE.Vector3(0, -0.25, 0);
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x72645b, 2, 15);
// Ground
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry(40, 40),
new THREE.MeshPhongMaterial({ color: 0x999999, specular: 0x101010 })
);
plane.rotation.x = -Math.PI / 2;
plane.position.y = -0.5;
scene.add(plane);
plane.receiveShadow = true;
var loader = new THREE.STLLoader();
// Binary files
var material = new THREE.MeshPhongMaterial({ color: 0xAAAAAA, specular: 0x111111, shininess: 200 });
loader.load('/productimages/mannequin.stl', function (geometry) {
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, -0.37, -0.6);
mesh.rotation.set(-Math.PI / 2, 0, 0);
mesh.scale.set(0.2, 0.2, 0.2);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
});
// Lights
scene.add(new THREE.AmbientLight(0x777777));
addShadowedLight(1, 1, 1, 0xffffff, 1.35);
addShadowedLight(0.5, 1, -1, 0xffaa00, 1);
// renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
renderer.shadowMapCullFace = THREE.CullFaceBack;
container.appendChild(renderer.domElement);
// stats
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
//
window.addEventListener('resize', onWindowResize, false);
}
function addShadowedLight(x, y, z, color, intensity) {
var directionalLight = new THREE.DirectionalLight(color, intensity);
directionalLight.position.set(x, y, z)
scene.add(directionalLight);
directionalLight.castShadow = true;
// directionalLight.shadowCameraVisible = true;
var d = 1;
directionalLight.shadowCameraLeft = -d;
directionalLight.shadowCameraRight = d;
directionalLight.shadowCameraTop = d;
directionalLight.shadowCameraBottom = -d;
directionalLight.shadowCameraNear = 1;
directionalLight.shadowCameraFar = 4;
directionalLight.shadowMapWidth = 1024;
directionalLight.shadowMapHeight = 1024;
directionalLight.shadowBias = -0.005;
directionalLight.shadowDarkness = 0.15;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
var timer = Date.now() * 0.0005;
camera.position.x = Math.cos(timer) * 3;
camera.position.z = Math.sin(timer) * 3;
camera.lookAt(cameraTarget);
renderer.render(scene, camera);
}
</script>

to stop it from spinning just remove the:
var timer = Date.now() * 0.0005;
camera.position.x = Math.cos(timer) * 3;
camera.position.z = Math.sin(timer) * 3;
from the render function or make a function to enable this part on click.

Related

Three.js: car orbit controls code won't work

I'm an absolute beginner in coding in general. I was trying to adapt the code for controlling a car from this codepeninto my project structure.
Here is my code:
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import "./styles.css";
// TASK 2
//let timer = setInterval(myTimer, 1000); //isn't it supposed to show something?
//function myTimer(){
// let d = new Date();
// document.getElementById("demo").innerHTML = d.toLocaleTimeString();
//}
// TASK 3.1
//document.getElementById("app").innerHTML =`
//<h1>Hello Vanilla</h1>
//<div>
// We use the same configuration as Parcel to bundle this sandbox, you can find more
// info about Parcel
// here
//</div>`
// TASK 3.2
let scene, camera, renderer;
let geometry, material, cube;
let colour, intensity, light;
let ambientLight;
let orbit, controls;
let listener, sound, audioLoader;
let clock, delta, interval, elapsedTime, lastElapsedTime, deltaTime, tick;
let sceneHeight, sceneWidth;
let size, divisions;
let car, body, bonnet, wheels;
let leftPressed, rightPressed, upPressed, downPressed;
let startButton = document.getElementById("startButton");
startButton.addEventListener("click", init);
function init() {
//alert("We have initialised!");
let overlay = document.getElementById("overlay");
overlay.remove();
sceneWidth = window.innerWidth;
sceneHeight = window.innerHeight;
//create our clock and set interval at 30 fpx
clock = new THREE.Clock();
delta = 0;
interval = 1 / 30;
lastElapsedTime = 0;
//create the scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xdfdfdf);
//create fog
const fog = new THREE.Fog(0xc3ebcd, 15, 40);
scene.fog = fog;
//creating camera (fos,aspect,near,far)
camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
camera.position.y = 5;
//skybox https://www.youtube.com/watch?v=PPwR7h5SnOE
let skyboxLoader = new THREE.CubeTextureLoader();
let skyboxTexture = skyboxLoader.load([
"./assets/skybox/xpos.png",
"./assets/skybox/xneg.png",
"./assets/skybox/ypos.png",
"./assets/skybox/yneg.png",
"./assets/skybox/zpos.png",
"./assets/skybox/zneg.png"
]);
scene.background = skyboxTexture;
//plane (ground) https://www.youtube.com/watch?v=PPwR7h5SnOE
let plane = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100, 1, 1),
new THREE.MeshStandardMaterial({ color: 0xc3ebcd })
);
plane.castShadow = false;
plane.receiveShadow = true;
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
//specify and adding renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//create orbit controls to interact with mouse
orbit = new OrbitControls(camera, renderer.domElement);
orbit.maxPolarAngle = 80 * (Math.PI / 180);
orbit.minDistance = 3;
orbit.maxDistance = 50;
orbit.enableDamping = true;
//CAR https://codepen.io/johndownie/pen/abjbLzy
car = new THREE.Group();
body = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: "blue",
roughness: 0.5
})
);
body.position.y = 0.2;
body.castShadow = true;
bonnet = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.5, 0.5),
new THREE.MeshStandardMaterial({
color: "blue",
roughness: 0.5
})
);
bonnet.position.z = -0.75;
bonnet.position.y = -0.25 + 0.2;
bonnet.castShadow = true;
wheels = [
{
name: "wheel1",
rotation: {
x: 0,
y: 0,
z: Math.PI * 0.5
},
position: {
x: 0.5 + 0.3 * 0.5,
y: -0.2,
z: 0.2
}
},
{
name: "wheel2",
rotation: {
x: 0,
y: 0,
z: -Math.PI * 0.5
},
position: {
x: -(0.5 + 0.3 * 0.5),
y: -0.2,
z: 0.2
}
},
{
name: "wheel3",
rotation: {
x: 0,
y: 0,
z: -Math.PI * 0.5
},
position: {
x: -(0.5 + 0.3 * 0.5),
y: -0.2,
z: -0.7
}
},
{
name: "wheel4",
rotation: {
x: 0,
y: 0,
z: Math.PI * 0.5
},
position: {
x: 0.5 + 0.3 * 0.5,
y: -0.2,
z: -0.7
}
}
];
for (let i = 0; i < wheels.length; i++) {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.3, 0.3, 10),
new THREE.MeshStandardMaterial({
color: 0x000000,
roughness: 0.5
})
);
wheel.rotation.set(
wheels[i].rotation.x,
wheels[i].rotation.y,
wheels[i].rotation.z
);
wheel.position.set(
wheels[i].position.x,
wheels[i].position.y,
wheels[i].position.z
);
wheel.name = wheels[i].name;
wheel.castShadow = true;
car.add(wheel);
}
car.add(body);
car.add(bonnet);
car.position.set(0, 0.5, 0);
scene.add(car);
//KEYBOARD SETUP
// Set up the key codes for the arrow keys
const LEFT_ARROW = 37;
const UP_ARROW = 38;
const RIGHT_ARROW = 39;
const DOWN_ARROW = 40;
// Set up a flag to track which keys are currently being pressed
let leftPressed = false;
let upPressed = false;
let rightPressed = false;
let downPressed = false;
// Listen for keydown events
document.addEventListener("keydown", function (event) {
// Check which key was pressed
switch (event.keyCode) {
case "LEFT_ARROW":
leftPressed = true;
break;
case UP_ARROW:
upPressed = true;
break;
case RIGHT_ARROW:
rightPressed = true;
break;
case DOWN_ARROW:
downPressed = true;
break;
default:
break;
}
});
// Listen for keyup events
document.addEventListener("keyup", function (event) {
// Check which key was released
switch (event.keyCode) {
case LEFT_ARROW:
leftPressed = false;
break;
case UP_ARROW:
upPressed = false;
break;
case RIGHT_ARROW:
rightPressed = false;
break;
case DOWN_ARROW:
downPressed = false;
break;
default:
break;
}
});
//First Person Camera https://www.youtube.com/watch?v=oqKzxPMLWxo
//controls = new FirstPersonControls(camera, renderer.domElement);
//controls.movementSpeed = 5;
//controls.lookSpeed = 0.8;
//fpsCamera = new FirstPersonCamera(this.camera, this.objects);
// lighting
colour = 0xffffff;
intensity = 1;
light = new THREE.DirectionalLight(colour, intensity);
light.position.set(100, 100, 100);
light.target.position.set(0, 0, 0);
light.castShadow = true;
scene.add(light);
ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// create a box to spin
//geometry = new THREE.BoxGeometry();
//material = new THREE.MeshNormalMaterial(); // Change this from normal to Phong in step 5
//cube = new THREE.Mesh(geometry, material);
//cube.position.set(0, 1, 0);
//cube.castShadow = true;
//cube.receiveShadow = true;
//scene.add(cube);
//SOUND (for single source and single listener)
listener = new THREE.AudioListener();
camera.add(listener);
sound = new THREE.PositionalAudio(listener);
audioLoader = new THREE.AudioLoader();
audioLoader.load("./sounds/CPC_Basic_Drone_Loop.mp3", function (buffer) {
sound.setBuffer(buffer);
sound.setRefDistance(5); //a double value representing the reference distance for reducing volume as the audio source moves further from the listener – i.e. the distance at which the volume reduction starts taking effect. This value is used by all distance models.
sound.setDirectionalCone(180, 230, 0.1);
sound.setLoop(true);
sound.setVolume(0.5);
sound.play();
});
//resize window
window.addEventListener("resize", onWindowResize, false);
//strech goal: add gridHelper
size = 20;
divisions = 20;
//let gridHelper = new THREE.GridHelper(size, divisions);
//scene.add(gridHelper);
play();
}
//stop animation
function stop() {
renderer.setAnimationLoop(null);
}
// simple render function
function render() {
//controls.update(clock.getDelta());
camera.position.z = car.position.z + 8;
camera.position.x = car.position.x + 8;
camera.lookAt(car.position);
renderer.render(scene, camera);
}
//start animation
function play() {
//callback — The function will be called every available frame. If null is passed it will stop any already ongoing animation
renderer.setAnimationLoop(() => {
update();
render();
});
}
//our update function
function update() {
//orbit.update();
//cube.rotation.x += 0.01;
//cube.rotation.y += 0.04;
//cube.rotation.z -= 0.01;
tick = () => {
elapsedTime = clock.getElapsedTime();
deltaTime = elapsedTime - lastElapsedTime;
lastElapsedTime = elapsedTime;
// Update the car's rotation based on which arrow keys are being pressed
if (leftPressed) {
car.rotation.y += Math.PI / 45; // Rotate the car 4 degree clockwise
}
if (rightPressed) {
car.rotation.y -= Math.PI / 45; // Rotate the car 4 degree counterclockwise
}
const vector = new THREE.Vector3(); // create once and reuse it!
// Get the car's forward direction vector
const forward = car.getWorldDirection(vector);
// Set up the speed at which the car will move
const CAR_SPEED = deltaTime * 20;
// Update the car's position based on its forward direction and speed
if (upPressed) {
car.position.x -= forward.x * CAR_SPEED;
car.position.y -= forward.y * CAR_SPEED;
car.position.z -= forward.z * CAR_SPEED;
car.getObjectByName("wheel1").rotation.x -= CAR_SPEED;
car.getObjectByName("wheel2").rotation.x -= CAR_SPEED;
car.getObjectByName("wheel3").rotation.x -= CAR_SPEED;
car.getObjectByName("wheel4").rotation.x -= CAR_SPEED;
}
if (downPressed) {
car.position.x += forward.x * CAR_SPEED;
car.position.y += forward.y * CAR_SPEED;
car.position.z += forward.z * CAR_SPEED;
car.getObjectByName("wheel1").rotation.x += CAR_SPEED;
car.getObjectByName("wheel2").rotation.x += CAR_SPEED;
car.getObjectByName("wheel3").rotation.x += CAR_SPEED;
car.getObjectByName("wheel4").rotation.x += CAR_SPEED;
}
// Update controls
// controls.update();
// Call tick again on the next frame
window.requestAnimationFrame(tick);
};
tick();
}
function onWindowResize() {
sceneHeight = window.innerHeight;
sceneWidth = window.innerWidth;
renderer.setSize(sceneWidth, sceneHeight);
camera.aspect = sceneWidth / sceneHeight;
// Always call updateProjectionMatrix on camera change
//camera.updateProjectionMatrix();
}
Any help is much appreciated!!
However, not sure if I put the loops in the right function (whether update or renderer function). The car won't move.

Three.js THREE.DeviceOrientationControls is not a constructor

I have a problem with ThreeJS giving me this error message. I included all the necessary ThreeJS files but still this message appears. My intention is to have a mobile device navigating with DeviceOrientationControl.js. Mousemove works very well, but I can't get this to work. Any ideas?
Uncaught TypeError: THREE.DeviceOrientationControls is not a constructor
at init ((index):201)
at (index):193
Error Message
<script type="module">
import * as THREE from '/bftest/three/build/three.module.js';
import {OrbitControls} from '/bftest/three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from '/bftest/three/examples/jsm/loaders/GLTFLoader.js';
import {DeviceOrientationControls} from '/bftest/three/examples/jsm/controls/DeviceOrientationControls.js';
var camera, scene, renderer, stats, controls, windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
var renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMapSoft = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var width = window.innerWidth;
var height = window.innerHeight;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
controls = new THREE.DeviceOrientationControls(camera);
camera.position.set(0, 0, 8);
scene = new THREE.Scene();
var directionalLight = new THREE.DirectionalLight(0xffffff, 5);
directionalLight.color.setHSL(0.1, 1, 0.95);
directionalLight.position.set(0, 1, 1);
directionalLight.position.multiplyScalar(10);
scene.add(directionalLight);
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
directionalLight.shadow.camera.left = -20;
directionalLight.shadow.camera.right = 20;
directionalLight.shadow.camera.top = 20;
directionalLight.shadow.camera.bottom = -20;
directionalLight.shadow.camera.near = 1;
directionalLight.shadow.camera.far = 200;
directionalLight.shadowCameraVisible = true;
var spotLight1 = new THREE.DirectionalLight( 0xff4000 );
spotLight1.position.set( -15, 3, -4 );
spotLight1.target.position.set( 0, 1, 0 );
spotLight1.intensity = 1.2;
spotLight1.shadowDarkness = 0.5;
spotLight1.shadowcameranear = 0;
spotLight1.shadowcamerafar = 15;
spotLight1.shadowcameraleft = -5;
spotLight1.shadowcameraright = 5;
spotLight1.shadowcameratop = 5;
spotLight1.shadowcamerabottom = -5;
spotLight1.castShadow = true;
scene.add( spotLight1 );
var spotLight2 = new THREE.DirectionalLight( 0xff0aea );
spotLight2.position.set( 15, 3, -4 );
spotLight2.target.position.set( 0, 1, 0 );
spotLight2.intensity = 1.2;
spotLight2.castShadow = true;
scene.add( spotLight2 );
var hemisphereLight = new THREE.HemisphereLight(0xffffff,0x000000, .5)
var shadowLight = new THREE.DirectionalLight(0xff8f16, .4);
shadowLight.position.set(50, 0, 22);
shadowLight.target.position.set(50, 50, 0);
shadowLight.rotation.set(Math.PI / -2, 0, 0);
shadowLight.shadow.camera.near = 0.5;
shadowLight.shadow.camera.far = 5000;
shadowLight.shadow.camera.left = -500;
shadowLight.shadow.camera.bottom = -500;
shadowLight.shadow.camera.right = 500;
shadowLight.shadow.camera.top = 500;
scene.add(shadowLight);
var light2 = new THREE.DirectionalLight(0xfff150, .25);
light2.position.set(-600, 350, 350);
var light3 = new THREE.DirectionalLight(0xfff150, .15);
light3.position.set(0, -250, 300);
scene.add(hemisphereLight);
scene.add(shadowLight);
const gltfLoader = new GLTFLoader();
gltfLoader.load('./3D/Bobby.glb', (gltf) => {
const root = gltf.scene;
root.rotateY(-89.55);
root.position.set(0, -0.7, 0);
root.castShadow = true;
gltf.scene.traverse(function(node) {
if (node instanceof THREE.Mesh) {
node.castShadow = true;
}
});
scene.add(root);//default is false
// compute the box that contains all the stuff
// from root and below
const box = new THREE.Box3().setFromObject(root);
const boxSize = box.getSize(new THREE.Vector3()).length();
const boxCenter = box.getCenter(new THREE.Vector3());
// set the camera to frame the box
frameArea(boxSize * 0.7, boxSize, boxCenter, camera);
box.castShadow = true;
// update the Trackball controls to handle the new size
controls.maxDistance = boxSize * 10;
controls.target.copy(boxCenter);
});
renderer = new THREE.WebGLRenderer({ antialias: true, canvas: document.querySelector('canvas'), alpha: true, });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
mouseX = - (event.clientX - windowHalfX) /150;
mouseY = - (event.clientY - windowHalfY) /150;
}
function animate() {
requestAnimationFrame(animate);
render(scene,camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function render() {
camera.position.x += (mouseX - camera.position.x)*0.9;
camera.position.y += (-mouseY - camera.position.y)*0.9;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
When importing examples files like DeviceOrientationControls via ES6 modules, using the THREE namespace is not necessary anymore. So instead of
controls = new THREE.DeviceOrientationControls(camera);
use
controls = new DeviceOrientationControls(camera);

three.js json loadingmanager model not displayed

I want to preload all models and textures with a loadingbar in my project. For that i use the LoadingManger from three.js but i have problems with preloading the json Models. They load but i am unable to display them. Here is an example.
You can see in the console that 200 Meshs are created. 100 For the Asteroids and 100 for the Ships.
Withoud the LoadingManger i can display the models (asteroids) so there should be no problem with the model. You can see in the example Asteroids that are loaded without the loading manager.
Here my simplified code for the problem
$(function(){
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var debugScene = true;
var controler, camera, controls, scene, renderer;
var objectControls;
var ship1geometry,ship1material;
////////////////////////////////////////////////////////
//LOADMANGER
////////////////////////////////////////////////////////
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (ship1geometry) {
var ship1material = new THREE.MeshFaceMaterial();
}, "models");
function init() {
var width = window.innerWidth;
var height = window.innerHeight;
camera = new THREE.PerspectiveCamera( 45, width / height, 1, 10000000 );
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 1500;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor("black");
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
var container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
controls.minDistance = 50;
controls.maxDistance = 300000;
controls.autoRotate = false;
controls.autoRotateSpeed = 0.05;
controls.target.x = 0;
controls.target.y = 0;
controls.target.z = 0;
light = new THREE.AmbientLight( 0x666666 );
scene.add( light );
light = new THREE.PointLight( 0xffffff, 1, 10000 );
light.position.set( 0, 0, 0 );
var params = { recursive: true };
objectControls = new ObjectControls( camera, params );
shipCount = 100;
for (var p = 0; p < shipCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var ship = createShipMesh(pX,0,pZ,0,0,0,ship1geometry,ship1material);
scene.add(ship);
}
var loader = new THREE.JSONLoader();
loader.load('models/asteroid.json', function (geometry, mat) {
var material = new THREE.MeshFaceMaterial( mat );
asteroidCount = 100;
for (var p = 0; p < asteroidCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( pX, 0, pZ );
scene.add(mesh);
}
}, "textures");
window.addEventListener( 'resize', onWindowResize, false );
if(debugScene){
var gridHelper = new THREE.GridHelper( 900000, 10000 );
gridHelper.setColors( 0x0000ff, 0x808080 );
scene.add( gridHelper );
var axisHelper = new THREE.AxisHelper( 500 );
scene.add( axisHelper );
console.log(scene);
}
}
function onWindowResize() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
var lastTimeMsec= null;
var nowMsec= null;
function animate() {
requestAnimationFrame( animate );
render();
update();
}
function update(){
controls.update();
objectControls.update();
}
function render() {
renderer.render( scene, camera );
}
function createShipMesh(positionX,positionY,positionZ,centerX,centerY,centerZ,geometry,material){
positionX = centerX + positionX;
positionY = centerY + positionY;
positionZ = centerZ + positionZ;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( positionX, positionY, positionZ );
objectControls.add( mesh );
mesh.select = function(){
controls.target.x = position.x;
controls.target.y = position.y;
controls.target.z = position.z;
controls.dollyIn(2);
controls.minDistance = 20;
}
return mesh;
}
});
Okay i found the problem on my own. the Loading Manager works with json but my mistake was to set the variable ship1geometry global and was thinking that the loader would overwrite this variable so that i can use it later in the scene. That was wrong. I just needed to assign the response from the loader in my globaly set variable. So here is the right code
var ship1geometry,ship1material
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (geometry,mat) {
ship1geometry = geometry;
ship1material = new THREE.MeshLambertMaterial({map:mat });
}, "textures");
function init(){
...
}

HTML5 canvas drawing on background scalling

i have problem i have background image and changing it scale and position with mousewheel and can drawing with mousedown and mousemove events. me example: http://jsfiddle.net/74MCQ/ Now see first drawing and second zoom we don't see drawing lines. I need make like a paint if drawing on me select position and if zoom i need see equal position with equal zoom scale.
You need a way to store the drawings of your user, either within another canvas, or by storing coordinates.
I suggest you store coordinates, below here's some code that will store the lines within an array, each line being an array of coordinates like : [x0, y0, x1, y1, x2, y2, ... ].
Edit : now i simplified the things, the coordinates are stored relative to the center of canvas.
See the fiddle, it is mostly working.
fiddle :
http://jsfiddle.net/gamealchemist/74MCQ/4/
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
var x = evt.clientX - rect.left;
var y = evt.clientY - rect.top;
var sx = (x-cw/2)/scale;
var sy = (y-ch/2)/scale;
return {
x: x,
y: y,
sx : sx,
sy:sy
};
}
/****** PAINT ******/
var isDrawing = false;
var color = "#000000";
var brushWidth = 10;
//var previousEvent = false;
ctx.strokeStyle = '#000000';
var currentLine = null;
var allLines = [];
$("#canvas").mousedown(function (e) {
var mousePos = getMousePos(canvas, e);
ctx.moveTo(mousePos.x, mousePos.y);
isDrawing = true;
if (currentLine) allLines.push(currentLine);
currentLine = [];
currentLine.push(mousePos.sx, mousePos.sy);
});
$("#canvas").mouseup(function () {
isDrawing = false;
if (currentLine) allLines.push(currentLine);
currentLine = null;
});
$("#canvas").mouseout(function () {
isDrawing = false;
if (currentLine) allLines.push(currentLine);
currentLine = null;
});
$("#canvas").mousemove(function (e) {
if (isDrawing === true) {
var mousePos = getMousePos(canvas, e);
currentLine.push(mousePos.sx, mousePos.sy);
//paint tools, effects
ctx.lineWidth = 10;
ctx.strokeStyle = color;
ctx.shadowBlur = 1;
ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.lineTo(mousePos.x, mousePos.y);
ctx.stroke();
}
});
function drawStoredLines() {
var thisLine;
for (var i = 0; i < allLines.length; i++) {
thisLine = allLines[i];
drawLine(thisLine);
}
}
function drawLine(ptArray) {
if (ptArray.length <= 2) return;
ctx.beginPath();
ctx.moveTo(ptArray[0], ptArray[1]);
for (var p = 2; p < ptArray.length; p += 2) {
ctx.lineTo(ptArray[p], ptArray[p + 1]);
}
ctx.lineWidth = 10;
ctx.strokeStyle = color;
ctx.shadowBlur = 1;
ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.stroke();
}
Notice that i couldn't resist reducing your 175 lines code to select the scale to a 25 lines one :-)
var zoomSteps = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0];
var zoomIndex = zoomSteps.indexOf(1);
function doScroll(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
zoomIndex = zoomIndex + delta;
if (zoomIndex < 0) zoomIndex = 0;
if (zoomIndex >= zoomSteps.length) zoomIndex = zoomSteps.length - 1;
scale = zoomSteps[zoomIndex];
imageWidthZoomed = imageWidth * scale;
imageHeightZoomed = imageHeight * scale;
var mousePos = getMousePos(canvas, e);
draw(mousePos.x, mousePos.y, scale);
}

HTML5, Easel.js game problems

Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt