You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Three.js中旋转对象时出现"Object is undefined"错误求助

Fixing the "Object is undefined" Error in Your Three.js Rotation Code

Hey there! That error is popping up because your object variable is declared but never actually assigned to a valid Three.js object (like a Mesh, Group, or loaded model) before the animate function tries to access its rotation property. Let's break this down and fix it.

The Root Cause

You've got var object; at the top, but there's no code that creates or assigns a proper Three.js object to this variable. When the animate loop runs, it tries to update object.rotation.x—but since object is still undefined, JavaScript throws that error.

How to Fix It

You need to initialize object with a valid Three.js object before starting the animation loop. Here's a complete example that adds a rotating cube, which should resolve the error:

// First set up your core Three.js components
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Create and assign your object here!
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
var object = new THREE.Mesh(geometry, material); // Assign the cube to your 'object' variable
scene.add(object); // Add it to the scene so it renders

camera.position.z = 5;

function render() {
  renderer.render(scene, camera);
}

function animate() {
  object.rotation.x += 0.1; // Now 'object' exists, so this won't throw an error
  render();
  requestAnimationFrame(animate);
  // Make sure 'controls' is initialized somewhere above this!
  if (controls) controls.update();
}

// Start the animation loop only after object is ready
animate();

Key Notes to Remember

  • If you're loading an external model (like GLTF/OBJ), start the animate loop only after the model finishes loading. Use the loader's callback to assign the model to object before calling animate().
  • Always double-check that variables holding scene objects are initialized before they're used in animation or rendering logic.
  • Don't forget to add your object to the scene—otherwise it won't show up even if it's correctly initialized!

内容的提问来源于stack exchange,提问作者Nuser0101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:03:44