I am utilizing three.js and OBJLoader to create a 3D human head representation:
let renderer, camera, scene, head, light, projectiles;
new THREE.OBJLoader().load(objUrl, initialize);
function initialize(obj) {
renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight);
scene = new THREE.Scene();
head = obj.clone();
head.children.forEach(child => child.material = new THREE.MeshPhongMaterial({ color: "#ffc700" }));
head.position.y = -34;
head.position.z = -110;
scene.add(head);
light = new THREE.SpotLight();
light.target = head;
scene.add(light);
projectiles = [];
window.addEventListener("mousedown", createProjectile, false);
animate();
}
function animate() {
head.rotation.y += THREE.Math.degToRad(1);
projectiles.forEach(updateProjectile);
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function createProjectile() {
let projectile = new THREE.Mesh();
projectile.material = new THREE.MeshToonMaterial({ color: "#ff0000" });
projectile.geometry = new THREE.SphereGeometry(3, 20, 20);
projectile.position.copy(getMouthPosition());
scene.add(projectile);
projectiles.push(projectile);
}
function updateProjectile(projectile) {
// TODO: Move projectile in the direction the mouth was facing when projectile was first created.
projectile.position.x += 2;
}
function getMouthPosition() {
// TODO: Determine the world position of the mouth.
let box = new THREE.Box3().setFromObject(head);
return box.getCenter();
}
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: 0;
}
canvas {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/86/three.js">
</script>
<script src="https://wzrd.in/standalone/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccb8a4bea9a9e1a3aea6e1a0a3ada8a9be8cfde2fde2ff">[email protected]</a>">
</script>
<script>
threeObjLoader(THREE);
objUrl = "https://cdn.rawgit.com/mrdoob/three.js/f32fc45/examples/obj/walt/WaltHead.obj";
</script>
On mouse click, I aim to launch a bullet/projectile from the moving head's mouth. However, there are two functions that need implementation, as indicated by the TODO
comments: getMouthPosition()
and updateProjectile()
.
To determine the current mouth position for getMouthPosition()
, I am looking to spawn the projectile slightly in front of the mouth.
Regarding updateProjectile()
, the goal is to move the projectile based on the direction the head was facing at the moment of creation.
If anyone has insights or suggestions on how to tackle these functions, it would be highly appreciated. Thank you.