camera中lookAt的理解

本文介绍了一个使用Three.js实现的物体跟踪示例,通过调整相机的lookAt目标点,确保物体始终位于屏幕中央。该方法适用于游戏开发和交互式3D应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

camera为相机看的目标点:因为屏幕显示的是相机视椎体的可视范围,而相机的lookAt方法指的是相机观察的目标点,故可以得出:

相机lookAt的点一定显示在屏幕的正中央:利用这点,我们可以实现物体移动时,我们可以一直跟踪物体,让物体永远在屏幕的中央:一下是代码实现

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>shape对象的研究</title>
    <style>
        body{
            margin:0;
        }
    </style>
</head>
<script src="../js/three.js"></script>
<script>
    function init() {
        createScene();
        buildAuxSystem();
        addBox();
        loop();
    }
    var scene,camera,renderer,width = window.innerWidth,height = window.innerHeight,controls;
    var box,x =0 ,z = 0;

    function createScene() {
        scene = new THREE.Scene;
        camera = new THREE.PerspectiveCamera(45,width/height,1,1000);
        camera.position.set(200,200,200);
        camera.lookAt(scene.position);

        renderer  = new THREE.WebGLRenderer();
        renderer.setClearColor(new THREE.Color(0x333333),1);
        renderer.setSize(width,height);
        document.body.appendChild(renderer.domElement);

        document.addEventListener("keydown",handleKey,false);
        window.addEventListener("resize",handleWindowResize,false)
    }
    function loop() {
        renderer.render(scene,camera);
        box.position.set(x,5,z);
        camera.lookAt(box.position);
        requestAnimationFrame(loop);
    }
    function handleWindowResize() {
        width = window.innerWidth;
        height = window.innerHeight;
        renderer.setSize(width,height);
        camera.aspect = width/height;
        camera.updateProjectionMatrix();
    }

    // 建立辅助设备系统
    function buildAuxSystem(){
        var gridHelper = new THREE.GridHelper(320,32);
        scene.add(gridHelper);

        var  axesHelper = new THREE.AxesHelper(320);
        scene.add(axesHelper);
    }
    function addBox() {
        var geometry = new THREE.CubeGeometry(10,10,10);
        box = new THREE.Mesh(geometry,new THREE.MeshBasicMaterial({color:0x00ff00}));
        box.position.set(x,5,z);
        scene.add(box);
    }

    function handleKey(e) {
        if(e.keyCode == 38){
            z -= 10;
        }else if(e.keyCode == 39){
            x += 10;
        }else{
            return;
        }
    }



</script>
<body onload ="init()">

</body>
</html>

效果:  当我们按  上 键 物体向上移动 屏幕视角也在移动,  当我们按  右键 物体向右移动, 屏幕也跟着向右移动。这样物体一直在屏幕的中央。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值