Cid-Wings
Cid-Wings

Reputation: 469

THREE.js blending two material on one mesh controlled by depth

I wanted to have two material .

mat1 =color red ; mat2 =color blue ;

Apply on a single mesh called "mesh1". The distance between the camera and the mesh is "1".

If mesh1 is close from the camera (0.1 - 0.4 ) mesh1 is red . If mesh1 is far from the camera (0.6 - 1 ) mesh1 is blue . During the transition (0,41-0,59) the depth control the transition the color of the object will be a gradient from red to blue .

Upvotes: 0

Views: 299

Answers (1)

Mugen87
Mugen87

Reputation: 31026

You don't need two materials for such an effect. Instead you can modulate the material's color based on the distance between the camera and the mesh. Check out this code:

var camera, scene, renderer;
var mesh;

var speed = 0.0005;

init();
animate();

function init() {

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

    scene = new THREE.Scene();

    var geometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 );
    var material = new THREE.MeshBasicMaterial();

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    mesh.position.z = Math.sin( performance.now() * speed );
        
    var d = mesh.position.distanceTo( camera.position );
        
    if ( d < 0.4 ) {
        
        mesh.material.color.set( 0xff0000 );
        
    } else if ( d > 0.6 ) {
        
        mesh.material.color.set( 0x0000ff );
        
    } else {
        
        var s = d - 0.4;
        var b = s / 0.2;
        var r = 1 - b;
            
        mesh.material.color.setRGB( r, 0, b );
        
    }

    renderer.render( scene, camera );

}
body {
      margin: 0;
}
canvas {
    display: block;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.js"></script>

Upvotes: 1

Related Questions