我ve seen different options to rotate objects but I don
知道如何应用它们。我是javascript的新手。我创建了立方体和球体,并设法使球体围绕自己的轴旋转,但我需要它围绕立方体旋转任何帮助都是受欢迎的。
这是我的代码:
<html>
<head>
<title>My first Three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
camera.position.z = 25;
var loader = new THREE.TextureLoader();
var texture = loader.load('crate.jpg');
var geometry = new THREE.BoxGeometry( 7, 7, 7 );
var material = new THREE.MeshBasicMaterial({map: texture});
var cube = new THREE.Mesh(geometry, material);
cube.rotation.x += 0.6;
cube.rotation.y += 0.6;
scene.add( cube );
var loader = new THREE.TextureLoader();
var texture = loader.load('earth.jpg');
var geometry = new THREE.SphereGeometry( 1, 50, 50 );
var material = new THREE.MeshBasicMaterial( {map: texture} );
var sphere = new THREE.Mesh( geometry, material );
scene.add( sphere );
var render = function () {
requestAnimationFrame( render );
sphere.position.set(6, 0, 15);
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
};
render();
</script>
</body>
</html>
答案 0 :(得分:0)
在这种情况下,我建议使用Object3D
作为球体的容器。然后将此容器放在立方体的位置/中心并旋转它。
...
var cube = new THREE.Mesh(geometry, material);
cube.rotation.x += 0.6;
cube.rotation.y += 0.6;
scene.add( cube );
...
var sphere = new THREE.Mesh( geometry, material );
sphere.position.set(0,0,15); // offset from center
var sphereContainer = new THREE.Object3D();
sphereContainer.add( sphere );
sphereContainer.position.copy( cube.position ); // optional, in case you've set the position of the cube
scene.add( sphereContainer );
var render = function () {
requestAnimationFrame( render );
sphere.rotation.y += 0.01; // rotate around its own axis
sphereContainer.rotation.y += 0.01; // rotate around cube
renderer.render(scene, camera);
};
答案 1 :(得分:0)
我找到了让它发挥作用的方法。我使用了rotateAboutWorldAxis函数,它看起来像这样:
...
sphere.position.set(0,0,15); // offset from center
function rotateAboutWorldAxis(object, axis, angle) {
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis( axis.normalize(), angle );
var currentPos = new THREE.Vector4(object.position.x, object.position.y, object.position.z, 1.5);
var newPos = currentPos.applyMatrix4(rotationMatrix);
object.position.x = newPos.x;
object.position.y = newPos.y;
object.position.z = newPos.z;
}
并在渲染函数中放置:
var yAxis = new THREE.Vector3(0,50,0);
rotateAboutWorldAxis(sphere,yAxis,Math.PI / 180);