Poyr23
Poyr23

Reputation: 123

Three.js ParametricGeometry animation (dynamically changing function)

I am really new to computer graphics, and I started experimenting with some things with THREE.js. So I wanted to an animation of a flag (wave motions) and I couldn't find anything (maybe I don't know what to search). So I made my flag with a parametric geometry, and the function is just a cos. And I wan't to animate the flag by dynamically changing the function of the parametric geometry. How can I do that, and is this the correct way of doing this?

P.S. The change in the function that I want is simply moving the cos along the X asis so it looks like the flag is moving.

Upvotes: 0

Views: 777

Answers (1)

prisoner849
prisoner849

Reputation: 17596

In dependency on amount of vertices in your mesh, you can use shaders or simple changing of vertices in your animation loop with cos function.

Below, there's the approach with simple changing.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 0, 2, 10 );
var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var controls = new THREE.OrbitControls( camera, renderer.domElement );

scene.add( new THREE.GridHelper( 10, 10 ) );

var planeGeom = new THREE.PlaneGeometry( 10, 3, 20, 3 );
var plane = new THREE.Mesh( planeGeom, new THREE.MeshBasicMaterial( { color: "red", side: THREE.DoubleSide } ) );
scene.add( plane );

render();
function render(){
  requestAnimationFrame( render );
  planeGeom.vertices.forEach( v => {
    v.z = Math.cos( .5 * v.x - Date.now() * .001 ) * .5;
  });
  planeGeom.verticesNeedUpdate = true; // the most important thing, when you change vertices
  renderer.render( scene, camera );
}
body{
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Upvotes: 2

Related Questions