- 序言
- 目录结构
- 代码一览
- world/Floor.js代码
- 代码解读
- 运行结果
目录结构通过上章的内容,对于地面创建的过程有了一定了解,本章将对代码进行升级,将定义的着色器应用到地面上。
资源目录里面的结构不变,点击传送门快速查看。
|__src
|__assets
|__js
| |__base 基础类文件夹
| |__Camera.js 相机类
| |__geometries 定制的物体类文件夹
| |__materials 材质类文件夹
| |__Floor.js 地面材质
| |__passes 合成器通道文件夹
| |__utils 工具类文件夹
| |__Sizes.js 画布大小控制类
| |__EventEmitter.js 基础事件处理器
| |__Time.js 动画刷新
| |__world 精灵类文件夹
| |__index.js 精灵类
| |__Floor.js 地面类【新增--着色器材质的应用】
| |__Application.js 初始化游戏的文件
|__index.js 入口
|__index.css 小项目,样式一丢丢
代码一览
world/Floor.js代码新增了对于着色器材质的纹理添加。
import * as THREE from "three";
import FloorMaterial from "../materials/Floor.js";
export default class Floor {
constructor(){
this.container = new THREE.Object3D();
this.container.matrixAutoUpdate = false;
this.geometry = new THREE.PlaneBufferGeometry(2, 2, 10, 10);
//===========新增内容开始===============
this.colors = {};
this.colors.topLeft = "#f5883c";
this.colors.topRight = "#ff9043";
this.colors.bottomRight = "#fccf92";
this.colors.bottomLeft = "#f5aa58";
this.material = new FloorMaterial();
this.updateMaterial();
//===========新增内容结束===============
this.mesh = new THREE.Mesh(this.geometry, this.material);
this.mesh.frustumCulled = false; //是否在渲染物体之前,检查每一帧的物体是否在摄像机的视锥体中
this.mesh.matrixAutoUpdate = false; //是否计算每一帧的位移、旋转(四元变换)和缩放矩阵,并重新计算matrixWorld属性
this.mesh.updateMatrix();
this.container.add(this.mesh)
}
updateMaterial(){
//生成顶点颜色对象
const topLeft = new THREE.Color(this.colors.topLeft);
const topRight = new THREE.Color(this.colors.topRight);
const bottomRight = new THREE.Color(this.colors.bottomRight);
const bottomLeft = new THREE.Color(this.colors.bottomLeft);
//使用颜色数据创建缓冲区
const data = new Uint8Array([
Math.round(bottomLeft.r * 255),
Math.round(bottomLeft.g * 255),
Math.round(bottomLeft.b * 255),
Math.round(bottomRight.r * 255),
Math.round(bottomRight.g * 255),
Math.round(bottomRight.b * 255),
Math.round(topLeft.r * 255),
Math.round(topLeft.g * 255),
Math.round(topLeft.b * 255),
Math.round(topRight.r * 255),
Math.round(topRight.g * 255),
Math.round(topRight.b * 255),
]);
//使用缓冲区创建数据纹理
this.backgroundTexture = new THREE.DataTexture(data, 2, 2, THREE.RGBFormat);
//当一个纹素覆盖大于一个像素时,贴图将如何采样。默认值为THREE.LinearFilter, 它将获取四个最接近的纹素,并在他们之间进行双线性插值。 另一个选项是THREE.NearestFilter,它将使用最接近的纹素的值。
this.backgroundTexture.magFilter = THREE.LinearFilter;
this.backgroundTexture.needsUpdate = true; //下次使用纹理时触发一次更新
//gsls传参
this.material.uniforms.tBackground.value = this.backgroundTexture;
}
}
代码解读
world/Floor.js 中新增了纹理,通过创建四个角的颜色对象,呈现线性过渡。你可以通过将this.backgroundTexture.magFilter = THREE.LinearFilter注释或打开,清晰的看到整个地面的变化过程。相信对于数据纹理会有一定的认识。
运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)