I am currently delving into the world of Three JS as a novice in 3D programming. Following a tutorial from the book , I am working on a game where an avatar navigates through trees. My current challenge involves getting the camera to continuously focus on the back of the avatar while it moves within the 3D environment.
To achieve this, I have created a marker attached to the avatar for the camera to target. However, when I move the avatar, the camera does not follow along with it.
Below is my code snippet:
var scene = new THREE.Scene();
var aspectRatio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, aspectRatio, 1, 10000);
camera.position.z = 500;
// Additional code for creating avatar, trees, and animation
marker.add(camera); // Focus the camera on the marker.
function animate() {
requestAnimationFrame(animate);
// Additional code for animation logic
renderer.render(scene, camera);
}
document.addEventListener('keydown', function (event) {
var code = event.keyCode;
// Movement controls and animations based on key presses
});
animate();
body {
margin: 0px;
}
canvas {
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>First 3D avatar game</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r125/three.min.js"></script>
</head>
<body>
</body>
</html>
If you can identify what is causing the issue in my code and provide suggestions on how to rectify it, I would greatly appreciate it!