以下是使用Three.js实现目标实时移动的示例代码,该示例通过经纬度来控制目标的位置:
<!DOCTYPE html>
<html>
<head>
<title>Target Tracking</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100%; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/examples/js/libs/tween.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three-globe/2.1.0/three-globe.js"></script>
<script>
// Set up the scene
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 500);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Define the globe with Three.js Globe
var earthTexture = 'https://cdn.glitch.com/1270abb6-e8c9-46e6-8137-b554f592eb54%2Fworld-topo-bathy-200401-3x5400x2700.png?v=1617984118154';
var globe = new ThreeGlobe()
.texture(earthTexture)
.showAtmosphere(false)
.rotationSpeed(0.5)
.scaleFactor(0.75)
.enablePointerInteraction(false);
scene.add(globe);
// Define target object to track
var target = new THREE.Mesh(
new THREE.SphereGeometry(10, 32, 32),
new THREE.MeshBasicMaterial({color: 0xff0000})
);
scene.add(target);
// Define function to update target position with given latitude and longitude
function updateTargetPosition(lat, long) {
var radius = 200;
var phi = (90 - lat) * Math.PI / 180;
var theta = (180 - long) * Math.PI / 180;
target.position.x = radius * Math.sin(phi) * Math.cos(theta);
target.position.y = radius * Math.cos(phi);
target.position.z = radius * Math.sin(phi) * Math.sin(theta);
}
// Set initial target position
updateTargetPosition(0, 0);
// Define animation loop
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
// Start animation loop
animate();
</script>
</body>
</html>
在此示例中,我们通过Three.js Globe创建了地球,并在其上方添加了一个红色的目标对象。我们使用 updateTargetPosition()
函数将目标的位置设置为根据给定的经纬度计算所得的位置,然后在 animate()
函数中调用该函数以更新目标的位置。