41

Is there any way to move an object forward in Three.js?

Maybe I should convert the rotation.x,y,z to a vector, and deal with it. But I'm beginner, and I don't have any idea how to do it.

4 Answers 4

65

Object3D has some handy methods for that.

object.translateZ( 10 );
8
  • 1
    Thanks. And how to move the camera?
    – eqiproo
    Jun 22, 2012 at 16:13
  • 4
    @eqiproo camera.translateZ( 10 );
    – mrdoob
    Jun 23, 2012 at 2:58
  • 12
    @mrdoob Is it possible to make documentaion for threejs more elaborate? Apr 13, 2013 at 19:04
  • 7
    Not to nitpick but I wouldn't consider translateZ() "moving", but more teleporting. Moving when described with 3D objects usually implies that the object can be seen going a specified direction or manner. This method does change the location of the object though :)
    – Ian Steffy
    Oct 23, 2015 at 8:14
  • 5
    @Ian Steffy I if you repeat translateZ with small increments at some rate, the object will appear to be moving. Jun 30, 2016 at 5:13
8

Please use above answer of @mrdoob, creator of ThreeJS:

object.translateZ( delta );

===OLD ANSWER===

A tutorial that worked for older ThreeJS version: http://www.aerotwist.com/tutorials/getting-started-with-three-js/

// set position of YOUR_OBJECT
YOUR_OBJECT.position.x = 10;
YOUR_OBJECT.position.y = 50;
YOUR_OBJECT.position.z = 130;

More options:

var STEP = 10;
var newCubeMatrix = cube.matrix;        
newCubeMatrix.identity();
//newCubeMatrix.multiplySelf(THREE.Matrix4.rotationYMatrix(cube.rotation.y));
newCubeMatrix.multiplySelf(THREE.Matrix4.translationMatrix(cube.position.x, cube.position.y, cube.position.z + STEP));
cube.updateMatrix();

details posted here https://gamedev.stackexchange.com/questions/7490/translate-object-in-world-space-usings-its-local-rotation

5
  • 1
    Sorry, but I still do not know how to do it :S
    – eqiproo
    Jun 20, 2012 at 20:40
  • 1
    Do you have some snippet to start with? did you try any tutorial yet? Did you check the link? Tell me your concerns? Jun 20, 2012 at 20:43
  • 1
    I have a red cube in my scene, which is rotated around the x,y and z axist. I would like to use the current direction of the object and move it forward using a specified step value.
    – eqiproo
    Jun 20, 2012 at 20:54
  • 1
    This answer is so old it needs to be taken down. None of this is correct with the latest ThreeJS
    – Tyguy7
    Aug 16, 2018 at 23:52
  • 2
    @Tyguy7 thanks for checking this, it was 6 years ago, lol. Just updated the answer so viewers won't deflect from the truth. Aug 18, 2018 at 4:57
7

The camera is a point in space. "Forward" is another point in space. so you can simply use the coordinates of a second point, and make the camera location closer to the "forward" location.

however, you may also need to turn left and right, which might involve polar coordinates.

adjust these values for your convenience:

var scene;
var camera;
var playerDirection = 0;//angles 0 - 2pi
var dVector;
var angularSpeed = 0.01;
var playerSpeed = 0.075;
var playerBackwardsSpeed = playerSpeed * 0.4;

this function will initialize the scene:

function init(){
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

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

    camera.position.z = 5;

    dVector = new THREE.Vector3( 0, 0, 0 ) ;
    camera.lookAt( dVector );

    animate();

}

movement of the player is stopped when the player presses the up key.

function key_up(event){
    playerIsMovingForward = 0;
    playerIsMovingBackwards = 0;
    playerIsRotatingLeft = 0;
    playerIsRotatingRight = 0;
    playerGoesUp = 0;
    playerGoesDown = 0;
}

when the player is moving, we update the position:

function updatePlayer(){
    if(playerIsRotatingLeft){ // rotate left
        playerDirection -= angularSpeed;
    }
    if(playerIsRotatingRight){ // rotate right
        playerDirection += angularSpeed;
    }
    if(playerIsRotatingRight || playerIsRotatingLeft){
        setPlayerDirection();

    }
    if(playerIsMovingForward){ // go forward
        moveForward(playerSpeed);

    }
    if(playerIsMovingBackwards){ // go backwards
        moveForward(-playerBackwardsSpeed);

    }

}

We assume by forward you meant "using the WASD keys"

function key_down(event){
    var W = 87;
    var S = 83;
    var A = 65;
    var D = 68;
    var minus = 189;
    var plus = 187;

    var k = event.keyCode;
    console.log(k);
    if(k == A){ // rotate left
        playerIsRotatingLeft = 1;
    }
    if(k == D){ // rotate right
        playerIsRotatingRight = 1;
    }
    if(k == W){ // go forward
        playerIsMovingForward = 1;
    }
    if(k == S){ // go back 
        playerIsMovingBackwards = 1;
    }


}

player will only move as fast as his browser. so maybe adjust this code?

function animate() {
    requestAnimationFrame( animate );

    updatePlayer();



    renderer.render( scene, camera );
}

this is the code that moves the camera into the position of the dVector object and also repositions the direction vector (dVector), so that it is always forward from the camera.

function moveForward(speed){
    var delta_x = speed * Math.cos(playerDirection);
    var delta_z = speed * Math.sin(playerDirection);
    var new_x = camera.position.x + delta_x;
    var new_z = camera.position.z + delta_z;
    camera.position.x = new_x;
    camera.position.z = new_z;

    var new_dx = dVector.x + delta_x;
    var new_dz = dVector.z + delta_z;
    dVector.x = new_dx;
    dVector.z = new_dz;
    camera.lookAt( dVector );    

}

moving forward usually involves turning left and right, here is some code that does that, it also uses polar coordinates, to move the point in relation to the camera (which is the center of the "circle" by a given amount of degrees (in radians)

function setPlayerDirection(){
    //direction changed.
    var delta_x = playerSpeed * Math.cos(playerDirection);
    var delta_z = playerSpeed * Math.sin(playerDirection);

    var new_dx = camera.position.x + delta_x;
    var new_dz = camera.position.z + delta_z;
    dVector.x = new_dx;
    dVector.z = new_dz;
    console.log(dVector);
    camera.lookAt( dVector ); 
}

animate();

I hope that helps.

3
  • 1
    This is a better approach. One thing to note here is returning after setPlayerDirection(); call in updatePlayer method will halt the player. Remove the return statement for smooth animation Apr 25, 2019 at 9:00
  • 1
    I'll try it out and get back with results. Apr 25, 2019 at 19:36
  • 1
    @HiteshSahu, I removed the return statements, the animation is a lot smoother now, may I ask how you got to that conclusion? Apr 26, 2019 at 17:03
3

Another option is to use Vector3's set method/function.

   position.set(x, y, z);
4
  • 1
    Something to Reflect on.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Sep 19, 2017 at 9:53
  • 1
    This was actually the answer I was looking for because "forward" was not precisely against the Z axis. +1
    – wizulus
    Dec 29, 2018 at 18:42
  • 1
    The translate methods are just aliases that perform this action--why is this answer being downvoted?
    – duhaime
    Jul 11, 2019 at 22:17
  • 1
    Ya that made no sense maybe up-vote it back to zero for the sake of common sense. Jul 12, 2019 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.