ThreeJS:实例化对象会将其位置设置为零



我在使用ThreeJS/Javascript时遇到了一些问题。我有一个玩家类和一个子弹类。当玩家类的"射击"变量为true时,它会创建子弹,将它们添加到数组中,并更新每个子弹。我遇到的问题是,子弹不是出现在玩家所在的地方,而是总是出现在世界空间0,0

这是玩家等级

var Player = function()
{
    this.lives = 3;
    this.upgrade = 0;
    this.bullets = [];
    this.shooting = false;
    //width, height, depth, health
    NPC.call(this, 50, 100, 50, 100);
    this.update = function()
    {
        if (this.shooting)
        {
            var b = new Bullet(this.position.clone() , new THREE.Vector3(0, 5, 0));
            scene.add(b);
            player.bullets.push(b);
            console.log(this.position);
            console.log(b.position);
        }

        for (var i = 0; i < this.bullets.length; i++)
        {
            this.bullets[i].update();
        }

    };


};

Player.prototype = Object.create(NPC.prototype);

这是子弹级

var Bullet = function(position, velocity)
{
    this.position = position;
    this.velocity = velocity;

    this.geometry = new THREE.CubeGeometry(5, 5, 5);
    this.material =  new THREE.MeshPhongMaterial({color: 0xFF0000});
    THREE.Mesh.call(this, this.geometry, this.material);

    this.update = function()
    {
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;
        this.position.z += this.velocity.z;
    };

};
Bullet.prototype = Object.create(THREE.Mesh.prototype);
Bullet.prototype.constructor = Bullet;

这是控制台每次更新的输出,第一个是玩家的位置,第二个是子弹的位置。每颗子弹的位置从零开始

THREE.Vector3{x:101.621837285986,y:87.1228026722121,z:999.99999999999977,构造函数:函数,集合:函数…}
THREE.Vector3{x:0,y:0,z:0,构造函数:函数,集合:函数…}

您在这里调用的是three.js Mesh构造函数:

THREE.Mesh.call(this, this.geometry, this.material);

此构造函数将position设置为新的0,0,0向量。由于您在自己设置position之后调用构造函数,因此它将重置为默认值。

只需将构造函数调用移到顶部即可。在我们进行此操作时,您也不必设置this.geometrythis.material——构造函数将为您执行此操作。通常情况下,在调用超类构造函数后进行自己的自定义,否则,它们可能会被覆盖。

最新更新