Okan Binli
Okan Binli

Reputation: 39

Different color on mesh's face towards to plane

I need to color a face looking towards to plane.

I thought two different approaches:

Is there any better way?

Upvotes: 0

Views: 69

Answers (1)

ScieCode
ScieCode

Reputation: 1735

As pointed out by @Mugen87, the easiest way to achieve that is by using custom shaders.

This is a wide topic, it might take some getting used to. But the are incredible resources out there explaining this topic in-depth. The Book of Shaders is a good place to start.


By calculating the dot product between a surface normal and the inverse view direction, you can get information about how much a certain surface is "facing" towards the camera.

Using this information we can mix two colors and use that as the final color that will appear on the screen.

<html>

<head>

<title> view-based color </title>

<style>
body { margin: 0; position: fixed;}
canvas { width: 100%; height: 100%; display: block;}
</style>

<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

</head>
<body>

<script>

var shader_vert = `

varying vec3 vNormal;

void main() {

	vNormal = normalize( modelMatrix * vec4( normal, 1.0 ) ).xyz;

	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

}

`;

var shader_frag = `

uniform vec3 viewDirection;

varying vec3 vNormal;

void main() {

	vec3 red = vec3( 1.0, 0.0, 0.0 );
	vec3 pink = vec3( 1.0, 0.8, 0.8 );

	float q = clamp( dot( vNormal, -viewDirection ), 0.0, 1.0 );

	vec3 color = mix( red, pink, q );

	gl_FragColor = vec4( color, 1.0 );


}

`;

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

var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

camera.position.set( 0, 2, 5 );
camera.lookAt( new THREE.Vector3() );


// plane
var geometry = new THREE.BoxBufferGeometry( 2, 2, 2 );

// custom shader
var material = new THREE.ShaderMaterial( {
	uniforms: {
		viewDirection: { value: new THREE.Vector3() }
	},
	vertexShader: shader_vert,
	fragmentShader: shader_frag,
} );
var plane = new THREE.Mesh( geometry, material );
scene.add( plane );


window.addEventListener( 'resize', onResize );


function animate() {

	requestAnimationFrame( animate );

	plane.rotation.y += 0.01;
	plane.rotation.x += 0.01;

	camera.getWorldDirection( material.uniforms.viewDirection.value );

	renderer.render( scene, camera );

};

function onResize() {

	var w = window.innerWidth;
	var h = window.innerHeight;

	camera.aspect = w / h;
	camera.updateProjectionMatrix();

	renderer.setSize( w, h );

}

animate();

</script>

</body>

</html>

Upvotes: 2

Related Questions