从Unity到Three.js(shader创建)

发布于:2024-02-27 ⋅ 阅读:(99) ⋅ 点赞:(0)

本文介绍three.js 中shader的创建和应用到模型,具体shader的语法和函数应用,已经有很多大佬总结过了。
three.js shader详解

import * as THREE from 'three';


const scene = new THREE.Scene();//创建场景
scene.background=new THREE.Color(0,0.1,0.2,1);//设置背景色
const geometry = new THREE.BoxGeometry(1, 1,1);//创建box物体
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);//配置相机参数
camera.position.z = 5;//设置相机位置

//顶点着色器
const vertex = `
varying vec2 vUv;//必须带varying
  void main() {
    vUv = uv;//记录UV信息
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);//顶点信息
  }
`;

//片元着色器
const fragment = `
varying vec2 vUv;//对应顶点着色器记录的UV信息
  void main() {
  
    //gl_FragColor = vec4(vUv.x, vUv.y, vUv.x, 1.0);
    //gl_FragColor = vec4(vec3(vUv.x), 1.0);
    //gl_FragColor = vec4(vUv, 0.0, 1.0);
    //gl_FragColor = vec4(step(0.5,vUv.x), step(0.5,vUv.y),1.0, 1.0);
    float color = step(0.5, vUv.x);
    float color2 = step(0.45,vUv.x);
    gl_FragColor = vec4(vec3(color2-color), 1.0);
    gl_FragColor = vec4(vec3(fract(vUv.x * 3.0)), 1.0);
    gl_FragColor = vec4(vec3(step(0.5,fract(vUv.x*5.0))),1.0)*vec4(vec3(step(0.5,fract(vUv.y*5.0))),1.0);


  }
`;
//创建对应shader的材质方法封装,获取对应shader的材质
function getMaterial()
{
    return new THREE.ShaderMaterial({
        vertexShader: vertex,
        fragmentShader: fragment
      });
}

const cube = new THREE.Mesh(geometry, getMaterial());
cube.position.x -= 2;
cube.position.y -= 2;
scene.add(cube);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
  }
  animate();

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到