我试图在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:我是新来的,这是我的第一篇文章,所以如果我在这篇文章中做错了,请告诉我,以便我可以从中学习。
答案 0 :(得分:1)
函数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);
}