1

The Goal

Im trying to make a simple camera zoom in animation that will zoom the camera in X amount every time the button is clicked.

The Current Progress

I current have the animation coded within Three.js and the buttons running running the script.

function cameraZoomIn() {
      console.log("Camera Zoom In Function Clicked");
      camera.position.z -= 50;
      requestAnimationFrame( cameraZoomIn );
      render();
};

<input type="button" onclick="cameraZoomIn();" value="Zoom Camera In!" />

The Problem

The animation runs however it runs forever as you can see here when clicking on the Zoom Camera In button - http://www.midlandgates.co.uk/three.js-master/examples/webgl_loader_obj.html

Update 1

If I remove requestAnimationFrame it will only run once however will jump to position not tween there. So why does this make the animation repeat itself?

WestLangley
  • 102,557
  • 10
  • 276
  • 276
Matt Hammond
  • 765
  • 1
  • 7
  • 25

1 Answers1

1

simply put: you're not checking if it should stop.

Basically you have a loop like:

while(true) {
   cameraZoomIn();
}

requestAnimationFrame() will always be called and executed whilst the page is in view.

You need to build in a check.

var intialz = camera.position.z;
var zoomfactor = 50;
function cameraZoomIn() {
  console.log("Camera Zoom In Function Clicked");
  camera.position.z -= zoomfactor;
  if(camera.position.z > (intialz - (zoomfactor * 10))) {// stop zooming at 10x zoom
      requestAnimationFrame( cameraZoomIn );
  }
  render();
};

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • if it helps you you could consider upvoting and accepting it. – Tschallacka Feb 10 '16 at 14:17
  • of course, I like to test it first before doing that, bare with me one second – Matt Hammond Feb 10 '16 at 14:18
  • 1
    I modified my example, because I realised I assumed initial camera z would be 0. modified it to go from the initial z value. Maybe add a function to reset z in your app or something to allow incremental zooming by pressing the button over and over. – Tschallacka Feb 10 '16 at 14:20
  • Yo thank you, such a simple fix!! Do you know the best way to rotate a object onClick, can't find anything out there – Matt Hammond Feb 10 '16 at 14:24
  • http://stackoverflow.com/questions/11060734/how-to-rotate-a-3d-object-on-axis-three-js – Tschallacka Feb 10 '16 at 14:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/103111/discussion-between-matt-hammond-and-michael-dibbets). – Matt Hammond Feb 10 '16 at 14:26