我正在尝试在三个.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);
}