Threejs - 创建一个类,无法通过位置变量传递 Vector3

Posted

技术标签:

【中文标题】Threejs - 创建一个类,无法通过位置变量传递 Vector3【英文标题】:Threejs - creating a class, unable to pass Vector3 through position variable 【发布时间】:2022-01-23 08:58:08 【问题描述】:

我尝试将 Vector3 的位置传递给 this.positon = position;,其中位置 == x、y、z。 即:0、2、0; joe = new people((0, 2, 0)) 但是,它不起作用。球体没有出现。我没有收到任何错误,当我 console.log(joe) 时,位置 = 0

class people 
constructor(name, age, color, position, radius)

    this.name = name,
    this.age = age,
    this.color = color,
    this.position = position,
    this.radius = radius,
    this.createperson()

createperson() // runs script below

    this.person = new THREE.Mesh(
        new THREE.SphereGeometry(this.radius, 32, 16),
        new THREE.MeshStandardMaterial(
            color: this.color,
            metalness: 0,
            roughness: 0.5
        )     
    )
    this.person.position.set(this.position)
    scene.add(this.person)

let joe = new people('Joe', 26, '#00ff00', (0, 1, 0), 2)

但是当我单独通过它时,this.x = x, this.y = y, this.z = zjoe = new people(0, 2, 0) 这行得通。它看起来应该如此。当我console.log(joe)时,位置是一个Vector3。

class people 
constructor(name, age, color, x, y, z, radius)

    this.name = name,
    this.age = age,
    this.color = color,
    this.x = x, // this
    this.y = y, // part
    this.z = z, // here works
    this.radius = radius,
    this.createperson()

createperson() // runs script below

    this.person = new THREE.Mesh(
        new THREE.SphereGeometry(this.radius, 32, 16),
        new THREE.MeshStandardMaterial(
            color: this.color,
            metalness: 0,
            roughness: 0.5
        )     
    )
    this.person.position.set(this.x, this.y, this.z)
    scene.add(this.person)

let joe = new people('Joe', 26, '#00ff00', 0, 1, 0, 2)

【问题讨论】:

this.person.position.set(this.position) 它必须是这样的this.person.position.copy(this.position)copy 而不是set,因为您在这里使用 Vector3,而不是使用单独的向量值) 【参考方案1】:

让 joe = new people('Joe', 26, '#00ff00', (0, 1, 0), 2) => let joe = new people('Joe', 26, '#00ff00', new THREE.Vector3(0, 1, 0), 2)

this.person.position.set(this.position) => this.person.position.copy(this.position)

【讨论】:

你是个天才,它行得通!非常感谢。

以上是关于Threejs - 创建一个类,无法通过位置变量传递 Vector3的主要内容,如果未能解决你的问题,请参考以下文章

ThreeJS简介

threejs学习day3:几何形状

threejs设置物体位置

2. threejs源码阅读——math/matrix

ThreeJS:更新相机 FOV

Threejs核心API