Home > Blockchain >  ThreeJS - on click move camera doesn't work
ThreeJS - on click move camera doesn't work

Time:07-02

I'm new with ThreeJS, so hopefully someone can help.

I'm trying to move my camera when I click the button, but nothing happens and I have no errors.

This is the function I have that should move camera by 200 in all directions, but no such effect:

var button = document.getElementById("button");
button.addEventListener("click", function() {
    var tween1 = new TWEEN.Tween(camera.position)
    .to({
        x : 200,
        y : 200,
        z : 200
    } , 1000)
    .easing(TWEEN.Easing.Linear.None)
    .start();
});

What am I doing wrong?

Here is the entire ThreeJS script for better context:

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 4;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;

var keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);

var fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);

var backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();

scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath('assets/');
mtlLoader.setPath('assets/');
mtlLoader.load('r2-d2.mtl', function (materials) {

    materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('assets/');
    objLoader.load('object.obj', function (object) {

        scene.add(object);
        object.position.y -= 0;

    });

});

var animate = function () {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render(scene, camera);
};

animate();

var button = document.getElementById("button");
button.addEventListener("click", function() {
    var tween1 = new TWEEN.Tween(camera.position)
    .to({
        x : 200,
        y : 200,
        z : 200
    } , 1000)
    .easing(TWEEN.Easing.Linear.None)
    .start();
});

CodePudding user response:

The first thing to do, when you work with Tween.js, is add

TWEEN.update()

to your animation loop.

  • Related