gpt4 book ai didi

javascript - 三JS : Instantiating an object sets its position to zero?

转载 作者:行者123 更新时间:2023-11-28 01:46:56 25 4
gpt4 key购买 nike

总的来说,我在使用 ThreeJS/Javascript 时遇到了一些麻烦。我有一个 Player 类和一个 Bullet 类。当玩家类的“射击”变量为 true 时,它​​会创建子弹,将它们添加到数组中,并更新每个子弹。我遇到的问题是,子弹不是出现在玩家所在的位置,而是始终出现在世界空间 0,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.62018337285986, y: -87.19228026722121, z: 99.99999999999977, constructor: function, set: function…}
THREE.Vector3 {x: 0, y: 0, z: 0, constructor: function, set: function…}

最佳答案

您正在此处调用 Three.js Mesh 构造函数:

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

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

只需将构造函数调用移至顶部即可。当我们这样做时,您也不必设置 this.geometrythis.material - 构造函数会为您完成此操作。一般来说,在调用父类(super class)构造函数后进行您自己的自定义 - 否则,它们可能会被覆盖。

关于javascript - 三JS : Instantiating an object sets its position to zero?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com