天天看點

threejs 形狀幾何體,僅擴充Three.js幾何體

threejs 形狀幾何體,僅擴充Three.js幾何體

I'm trying to scale the geometries y-axis. This made my cube scale both up and down. I think mesh.transformY works to animate the cube up half of the scaling value. This would make it look like the cube just scaled upwards. Are there other solutions for this?

var geometry = new THREE.BoxGeometry(1, 1, 1);

var mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({

color: 0xffffff

}));

mesh.position.set(0, 2, 0);

mesh.scale.set(0.98, 0.95, 0.992);

mesh.castShadow = true;

scene.add(mesh);

var tween = new TWEEN.Tween(mesh.scale)tween.to({y: 2}, 1000)

tween.easing(TWEEN.Easing.Elastic.InOut);

tween.yoyo(true);

tween.start();

解決方案

The usual case of your question is something on a 'ground', like a 'person' mesh, that shall always have its feet on the ground whatever its size. There are two ways for that.

The way Evilzebra proposed in the comment. Based on the height of your mesh you can implement it easily : as you wrote, when scaling in y, the mesh will get half taller both on top and bottom. So you just have to move its position to height * scale / 2 :

function scaleY ( mesh, scale ) {

mesh.scale.y = scale ;

if( ! mesh.geometry.boundingBox ) mesh.geometry.computeBoundingBox();

var height = mesh.geometry.boundingBox.max.y - mesh.geometry.boundingBox.min.y;

//height is here the native height of the geometry

//that does not change with scaling.

//So we need to multiply with scale again

mesh.position.y = height * scale / 2 ;

}

Another way is to move the origin of the coordinates (local space) at the bottom of the geometry, so the position is not changed. For that you have to move the origin of the geometry to the lowest y coordinate. You will then be able to change your scale at will with the native ThreeJS method :

function originToBottom ( geometry ) {

//1. Find the lowest `y` coordinate

var shift = geometry.boundingBox ? geometry.boundingBox.min.y : geometry.computeBoundingBox().min.y;

//2. Then you translate all your vertices up

//so the vertical origin is the bottom of the feet :

for ( var i = 0 ; i < geometry.vertices.length ; i++ ) {

geometry.vertices[ i ].y -= shift;

}

//or as threejs implements (WestLangley's answer) :

geometry.translate( 0, -shift, 0);

//finally

geometry.verticesNeedUpdate = true;

}