(Three.JS) 如何通过两种以上的颜色三种颜色循环/lerp?

问题描述

我正在 Three.JS 在线编辑器中处理一个项目。 我正在尝试进行日/夜循环。 它应该循环颜色,设置场景背景颜色,如下所示:

  1. 日出/日落
  2. 夜晚
  3. 日出/日落
  4. 日 ... 等等等等,

它应该永远循环遍历这些。

我已经让它遍历了两种颜色,但我似乎无法让它遍历所有三种颜色。

有没有办法做到这一点? 到目前为止,这是我的代码:

//var day = new THREE.Color(0xB8F4FF);
//var duskdawn = new THREE.Color(0xFF571F);
//var night = new THREE.Color(0x17012D);

//scene.background = new THREE.Color(0xB8F4FF);

let t = 0;
let tn = 0;
let cyc = 0;

//const day = new THREE.Color(0xB8F4FF);
var day = new THREE.Color(0xB8F4FF);
const duskdawn = new THREE.Color(0xFF571F);
const night = new THREE.Color(0x17012D);

animate();

function animate() {

  requestAnimationFrame(animate);
  t += 0.01;
  tn += 0.01;
  cyc = 0.9;
  cyc += 0.1;
  if(cyc % 2 == 1){
      //day = new THREE.Color(0x17012D);
      day = new THREE.Color(0xB8F4FF);
      //scene.background.copy(day).lerp(duskdawn,0.5 * (Math.sin(t) + 1));
      scene.background.copy(day).lerp(duskdawn,0.5 * (Math.sin(t) + 1));
      day = new THREE.Color(0x17012D);
      cyc += 0.1;
      if(cyc != 1){
          day = new THREE.Color(0x17012D);
      }
  /**/
  }
  if(cyc % 2 != 0){
      //scene.background.copy(night).lerp(duskdawn,0.5 * (Math.sin(tn) + 1));
      //day = new THREE.Color(0xB8F4FF);
      day = new THREE.Color(0x17012D);
      scene.background.copy(day).lerp(duskdawn,0.5 * (Math.sin(tn) + 1));
      //day = new THREE.Color(0xB8F4FF);
      cyc += 0.1;
      //cyc = 0;
  }
  /**/
  cyc = 0.9;
  cyc += 0.1;
  //cyc += 1;
}

任何帮助将不胜感激。

如果有人需要更多信息,请告诉我!

谢谢!

解决方法

试试看:

let camera,scene,renderer,clock;

const colors = [
  new THREE.Color(0xff0000),new THREE.Color(0xffff00),new THREE.Color(0x00ff00),new THREE.Color(0x0000ff)
];

const duration = 4; // 4s

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70,window.innerWidth / window.innerHeight,0.01,10);
  camera.position.z = 1;

  scene = new THREE.Scene();
  scene.background = new THREE.Color();

  clock = new THREE.Clock();

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth,window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

  const time = clock.getElapsedTime();

  animateBackground(time)

  renderer.render(scene,camera);

}

function animateBackground(t) {

  const f = Math.floor(duration / colors.length);
  const i1 = Math.floor((t / f) % colors.length);
  let i2 = i1 + 1;

  if (i2 === colors.length) i2 = 0;

  const color1 = colors[i1];
  const color2 = colors[i2];
  const a = (t / f) % colors.length % 1;

  scene.background.copy(color1);
  scene.background.lerp(color2,a);


}
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.124/build/three.js"></script>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...