无法在ThreeJS(3js)中为动态创建的盒子设置动画

时间:2019-10-11 22:32:47

标签: javascript three.js

我会尽量简化一下,我以前从未在网上问过运气。

所以基本上我在JS中编写了一个for循环,以便动态创建多个框状网格,以便可以使用3js为它们设置动画

var ghostBoxes = 10;
var boxes = [];

meshX = -10;
for (var i = 0; i < ghostBoxes; i++) {
  var ghostBox = new THREE.Mesh(geometry, material);
  ghostBox.position.x = (Math.random() - 0.5) * 10;
  ghostBox.position.y = (Math.random() - 0.5) * 10;
  ghostBox.position.z = (Math.random() - 0.5) * 10;
  scene.add(ghostBox);
  boxes.push(ghostBox);
  meshX += 1;
}

此脚本似乎很好用,因为它们看起来很好。此外,当我console.log(boxes.length)返回整数10时,我怀疑即时消息已成功填充数组。

但是,当我尝试对所有十个动画进行动画处理(带有一些简单的x和y轴旋转)时,我只能对一个动画进行动画处理(并且只能在一个轴上进行动画处理),参见下文...

var render = function() {
  requestAnimationFrame(render);

  renderer.render(scene, camera);
  for (var i = 0; i < ghostBoxes; i++) {
    this.tl = new TimelineMax();
    this.tl.to(boxes[i].rotation.x += 0.01, {x: 2, ease: Expo.easeOut});
    this.tl.to(boxes[i].rotation.y += 0.01, {x: .5, ease: Expo.easeOut});
  }
};

此外,我得到了...的无尽编译错误。

“ TweenMax.min.js:14未捕获的TypeError:无法读取未定义的属性'repeat'     在d.s.to(TweenMax.min.js:14)     在渲染时(main.js:52)”

js 52是我尝试在“ x”轴上旋转的第二行代码。

我的结构也可能偏离。我已经尝试了很多东西,但是我很难尝试更多。我完全卡住了。我只编码了3个月,所以请保持谦虚。

===>下面的整个代码

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000,
);
camera.position.z = 20;

var light = new THREE.PointLight(0xffffff, 1, 1000);
light.position.set(0, 0, 0);
scene.add(light);

var light = new THREE.PointLight(0xffffff, 2, 1000);
light.position.set(0, 0, 25);
scene.add(light);

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor('#ffffff');
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);
window.addEventListener('resize', () => {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
});

var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshLambertMaterial({ color: 0xf7f7f7 });

var ghostBoxes = 10;
var boxes = [];

meshX = -10;
for (var i = 0; i < ghostBoxes; i++) {
  var ghostBox = new THREE.Mesh(geometry, material);
  ghostBox.position.x = (Math.random() - 0.5) * 10;
  ghostBox.position.y = (Math.random() - 0.5) * 10;
  ghostBox.position.z = (Math.random() - 0.5) * 10;
  scene.add(ghostBox);
  boxes.push(ghostBox);
  meshX += 1;
}

var render = function() {
  requestAnimationFrame(render);

  renderer.render(scene, camera);
  for (var i = 0; i < ghostBoxes; i++) {
    this.tl = new TimelineMax();
    this.tl.to(boxes[i].rotation.x += 0.01, {x: 2, ease: Expo.easeOut});
    this.tl.to(boxes[i].rotation.y += 0.01, {x: .5, ease: Expo.easeOut});
  }
};

render(boxes);
// ghostBox.rotation.x += 0.01;
// ghostBox.rotation.y += 0.01;

谢谢

0 个答案:

没有答案