gpt4 book ai didi

javascript - 在 Three.js 中一次移动多个对象

转载 作者:行者123 更新时间:2023-12-03 04:07:14 25 4
gpt4 key购买 nike

我正在尝试在 Three.js 中同时移动多个球。我创建了一个创建球的函数,并使用它创建了三个球。后来我创建了一个移动球的函数,它适用于一个球,但每当我尝试一次移动所有球时,它就不起作用。任何帮助将非常感激。这是代码:

球功能:

function Ball(valuex, valuey, valuez, ballname, color)
{
var balMaterial, balGeometry, balMesh;
balMaterial = new THREE.MeshLambertMaterial({ color: color});
balGeometry = new THREE.SphereGeometry(0.3,50,50);
balMesh = new THREE.Mesh(balGeometry, balMaterial);
balMesh.position.set(valuex,valuey,valuez);
balMesh.name = ballname;
balMesh.ballDirection = new THREE.Vector3();
balMesh.ballDirection.x = -5;
balMesh.ballDirection.z = 1;
balMesh.ballDirection.normalize();
balMesh.moveSpeed = 25;
scene.add(balMesh);
}

移动球:

function moveBalls (ball) {
var tempbal = scene.getObjectByName(ball);
var ballDirection = tempbal.ballDirection;
tempbal.position.add(speed.copy(ballDirection).multiplyScalar(clock.getDelta() * tempbal.moveSpeed));



if (tempbal.position.x < -4.7) {
ballDirection.x = Math.abs(ballDirection.x);
}
if (tempbal.position.x > 4.7) {
ballDirection.x = -Math.abs(ballDirection.x);
}
if (tempbal.position.z > 12.2) {
ballDirection.z = -Math.abs(ballDirection.z);
}
if (tempbal.position.z < -12.2) {
ballDirection.z = Math.abs(ballDirection.z);
}
if (tempbal.moveSpeed > 0)
{
tempbal.moveSpeed = tempbal.moveSpeed - 0.002;
}
}

创建球:

Ball(0,4.5,0, "ball1", 0xffffff);
Ball(2,4.5,0, "ball2", 0xffffff);
Ball(0,4.5,6, "ball3", 0xff0000);

动画场景:

function animateScene()
{
moveBalls("ball1");
moveBalls("ball2");
moveBalls("ball3");
requestAnimationFrame(animateScene);

renderer.render(scene, camera);
}

PS:我是新来的,这是我的第一篇文章,所以如果我在这篇文章中做错了什么,请告诉我,以便我可以从中学习。

最佳答案

函数clock.getDelta()返回自上次调用clock.getDelta()以来经过的秒数,这意味着只有您的第一个球可以移动。事实上,第一个球调用了 getDelta()(它返回大于 0 的值)。在同一帧(意思是大约在同一时间),您为第二个球调用clock.getDelta(),它返回 0。第三个球也会发生同样的情况.

尝试执行以下操作:

function moveBalls (ball, deltaTime) {
var tempbal = scene.getObjectByName(ball);
var ballDirection = tempbal.ballDirection;
tempbal.position.add(speed.copy(ballDirection).multiplyScalar(deltaTime
* tempbal.moveSpeed));

if (tempbal.position.x < -4.7) {
ballDirection.x = Math.abs(ballDirection.x);
}
if (tempbal.position.x > 4.7) {
ballDirection.x = -Math.abs(ballDirection.x);
}
if (tempbal.position.z > 12.2) {
ballDirection.z = -Math.abs(ballDirection.z);
}
if (tempbal.position.z < -12.2) {
ballDirection.z = Math.abs(ballDirection.z);
}
if (tempbal.moveSpeed > 0)
{
tempbal.moveSpeed = tempbal.moveSpeed - 0.002;
}
}

// ...

function animateScene()
{
var deltaTime = clock.getDelta() ;
moveBalls("ball1", deltaTime);
moveBalls("ball2", deltaTime);
moveBalls("ball3", deltaTime);
requestAnimationFrame(animateScene);

renderer.render(scene, camera);
}

关于javascript - 在 Three.js 中一次移动多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44497622/

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