草庐IT

javascript - THREE.js:渲染后调用 lookAt 方法不起作用

coder 2025-03-01 原文

下面的脚本不能正常工作。 (它只需要 jquery 和 three.js 来运行)。麻烦的是这两行:

// change the view so looking at the top of the airplane
views[1].camera.position.set( 0,5,0 );
views[1].camera.lookAt(objectManager.airplane.position);

奇怪的是,如果这两行被注释掉,可以看出下面两行类似的前面的行确实按预期运行:

views[1].camera.lookAt(objectManager.airplane.position);

view.camera.position.set( 5,0,0 );

出于某种原因,对 camera.lookAt 的调用似乎只在第一次有效。之后,相机不再跟随飞机物体。如果有人能找出我做错了什么,我将不胜感激!

完整的脚本如下。

谢谢

$(function(){
    var scene, renderer, viewPort, objectManager, views;

    init();
    animate();

    function init() {
        viewPort = $('body');

        scene = new THREE.Scene();

        // construct the two cameras
        initialiseViews();

        // construct airplane, lights and floor grid
        objectManager = new ObjectManager();
        objectManager.construct();
        objectManager.addToScene(scene);

        // make the second camera's position
        // stay fixed relative to the airplane
        objectManager.airplane.add(views[1].camera);

        // make the second camera stay looking
        // at the airplane
        views[1].camera.lookAt(objectManager.airplane.position);

        renderer = new THREE.WebGLRenderer();
        renderer.setClearColorHex(0x000000, 1);
        renderer.setSize( viewPort.innerWidth(), viewPort.innerHeight() );
        viewPort.get(0).appendChild(renderer.domElement);
    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        objectManager.tick();
        for (var i in views){
            views[i].render(scene, renderer);
        }
    }
    function initialiseViews(){
        views = [];

        // ----------------------------------------------------
        // Create the first view, static with respect to ground
        // ----------------------------------------------------
        views[0] = new View(viewPort, objectManager, scene);
        var view = views[0];
        view.fov = 40;
        view.proportions.height = 0.5;
        view.proportions.bottom = 0.5;
        view.init();
        view.camera.position.y = 1;
        view.camera.position.z = 4;

        // ----------------------------------------------------
        // Create the second view, which follows the airplane
        // ----------------------------------------------------

        views[1] = new View(viewPort, objectManager, scene);
        var view = views[1];

        view.fov = 20;
        view.proportions.height = 0.5;
        view.init();

        // set the initial position of the camera
        // with respect to the airplane. Views from behind
        view.camera.position.set( 5,0,0 );

        view.updateCamera = function(){

            // change the view so looking at the top of the airplane
            views[1].camera.position.set( 0,5,0 );
            views[1].camera.lookAt(objectManager.airplane.position);

            views[1].camera.updateProjectionMatrix();
        };
    }
});
function View(viewport, om, scene){
    this.scene = scene;
    this.camera;
    this.objectManager = om;
    this.viewPort = viewport;
    this.fov = 30;
    // default: full width and height
    this.proportions = { left: 0, bottom: 0, height: 1, width: 1 };
    this.pixels = { left: 0, bottom: 0, height: 0, width: 0, aspect: 0 };
    this.aspect;
    this.init = function(){
        this.pixels.left = Math.floor(this.proportions.left * this.viewPort.innerWidth()); 
        this.pixels.width = Math.floor(this.proportions.width * this.viewPort.innerWidth()); 
        this.pixels.bottom = Math.floor(this.proportions.bottom * this.viewPort.innerHeight()); 
        this.pixels.height = Math.floor(this.proportions.height * this.viewPort.innerHeight()); 
        this.pixels.aspect = this.pixels.width / this.pixels.height;
        this.makeCamera();
    };
    this.makeCamera = function(){
        this.camera = new THREE.PerspectiveCamera( 
                this.fov, 
                this.pixels.aspect, 
                0.1, 10000 
        );
        this.camera.updateProjectionMatrix();
        this.scene.add(this.camera);
    };
    this.render = function(scene, renderer){
        this.updateCamera();
        pixels = this.pixels;
        renderer.setViewport(pixels.left, pixels.bottom, pixels.width, pixels.height);
        renderer.setScissor(pixels.left, pixels.bottom, pixels.width, pixels.height);
        renderer.enableScissorTest(true);
        renderer.render( scene, this.camera );
    };
    this.updateCamera = function(){};
}

function ObjectManager(){
    // manages all visible 3d objects (including lights)
    this.airplane;
    var grid;
    var ambientLight;
    var pointLight;
    this.construct = function(){
        this.constructAirplane();
        this.constructLights();
        this.constructFloorGrid();
    };
    this.constructAirplane = function(){
        this.airplane = new THREE.Object3D();
        var fuselage = newCube(
                {x: 1, y: 0.1, z: 0.1}, 
                {x: 0, y: 0, z: 0},
                [0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
                [0, 1, 2, 3, 4, 5]
        );
        this.airplane.add(fuselage);
        var tail = newCube(
                {x: 0.15, y: 0.2, z: 0.03}, 
                {x: 0.5, y: 0.199, z: 0},
                [0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
                [0, 1, 2, 3, 4, 5]
        );
        this.airplane.add(tail);
        var wings = newCube(
                {x: 0.3, y: 0.05, z: 1},    
                {x: -0.05, y: 0, z: 0},
                [0xffff00, 0x808000, 0x0000ff, 0xff00000, 0xffffff, 0x808080],
                [0, 1, 2, 3, 4, 5]
        );
        this.airplane.add(wings);
    };
    this.constructLights = function(){
        ambientLight = new THREE.AmbientLight(0x808080);
        pointLight = new THREE.PointLight(0x808080);
        pointLight.position = {x: 100, y: 100, z: 100};
    };
    this.constructFloorGrid = function(){
        grid = new THREE.Object3D();

        var geometry = new THREE.Geometry();
        geometry.vertices.push(new THREE.Vector3( - 200, 0, 0 ) );
        geometry.vertices.push(new THREE.Vector3( 200, 0, 0 ) );

        linesMaterial = new THREE.LineBasicMaterial( { color: 0x00ff00, opacity: 1, linewidth: .1 } );

        for ( var i = 0; i <= 200; i ++ ) {

            var line = new THREE.Line( geometry, linesMaterial );
            line.position.z = ( i * 2 ) - 200;
            grid.add( line );

            var line = new THREE.Line( geometry, linesMaterial );
            line.position.x = ( i * 2 ) - 200;
            line.rotation.y = 90 * Math.PI / 180;
            grid.add( line );
        }       
    };
    this.addToScene = function(scene){
        scene.add( this.airplane );
        scene.add( grid );
        scene.add( ambientLight );
        scene.add( pointLight );
    };
    this.tick = function(){
        this.airplane.rotation.x += 0.005;
        this.airplane.rotation.y += 0.01;
        this.airplane.position.x -= 0.05;
    };
};

function newCube(dims, pos, cols, colAss){
    var mesh;
    var geometry;
    var materials = [];
    geometry = new THREE.CubeGeometry( dims.x, dims.y, dims.z );
    for (var i in cols){
        materials[i] = new THREE.MeshLambertMaterial( { color: cols[i], ambient: cols[i], overdraw: true } );
    }
    geometry.materials = materials;
    for (var i in colAss){
        geometry.faces[i].materialIndex = colAss[i];
    }
    mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
    mesh.position = pos;
    return mesh;
}

最佳答案

你需要这样做:

views[1].camera.position.set( 0, 5, 0 );
views[1].camera.lookAt( new THREE.Vector3() );

不是这个:

views[1].camera.position.set( 0, 5, 0 );
views[1].camera.lookAt( objectManager.airplane.position );

你的相机是飞机的 child 。它需要在其本地坐标系中查看 ( 0, 0, 0 ) —— 而不是飞机在世界空间中的 位置

您不必调用 updateProjectionMatrix()。复制 three.js 示例。

关于javascript - THREE.js:渲染后调用 lookAt 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14772212/

有关javascript - THREE.js:渲染后调用 lookAt 方法不起作用的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

随机推荐