我对React.js和React-three-fiber是个新手。我想加100颗星。createStars()函数为循环运行100次,并创建100个x,y,z坐标。创建小球体。如何在循环中运行100次?
import './App.css';
import React, { useRef } from "react";
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from "react-three-fiber";
function App() {
function scrollPage() {
console.log('Heelo');
}
function createStars() {
console.log('Hello');
for(var i = 0; i < 100; i++) {
var x = Math.floor(Math.random() * 10);
var y = Math.floor(Math.random() * 10);
var z = Math.floor(Math.random() * 10);
console.log(x + ' ' + y + ' ' + z);
}
}
return (
<>
<Canvas colorManagement id="canvas">
<ambientLight intensity={1} />
<Star position={[0,0,0]} color='white' />
<Star position={[1,0,0]} color='white' />
<Star position={[0,3,0]} color='white' />
<Star position={[0,-3,0]} color='white' />
<Star position={[5,2,-3]} color='white' />
<Star position={[10,0,0]} color='white' />
<Star position={[-3,0,1]} color='white' />
<Star position={[-5,2,0]} color='white' />
<Star position={[-10,0,1]} color='white' />
<Star position={[-6,-5,-4]} color='white' />
<Star position={[-7,-3,0]} color='white' />
<Star position={[7,-2,0]} color='white' />
<Star position={[-7,3,0]} color='white' />
<Star position={[0,0,9]} color='white' />
</Canvas>
</>
);
}
const Star = ({position, color}) => {
const mesh = useRef(null);
useFrame(() => (mesh.current.rotation.x += 0.01));
return(
<>
<mesh position={position} ref={mesh}>
<sphereBufferGeometry attach='geometry' args={[0.02,500, 500]} />
<meshStandardMaterial attach='material' color={color}/>
</mesh>
</>
);
}
export default App;附注-忽略任何小的打字错误,代码运行良好。
发布于 2021-02-10 13:31:55
我相信您希望将Star组件映射到随机生成的坐标。
请看以下内容:
import './App.css';
import React, { useRef } from "react";
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from "react-three-fiber";
function App() {
function scrollPage() {
console.log('Heelo');
}
function createStars() {
let stars = []
for (var i = 0; i < 100; i++) {
var x = Math.floor(Math.random() * 10);
var y = Math.floor(Math.random() * 10);
var z = Math.floor(Math.random() * 10);
stars[i] = [x, y, z]
}
return stars
}
const stars = createStars().map((cords, i) =>
(<Star key={i} position={cords} color='white' />)
)
return (
<>
<Canvas colorManagement id="canvas">
<ambientLight intensity={1} />
{stars}
</Canvas>
</>
);
}
const Star = ({position, color}) => {
const mesh = useRef(null);
useFrame(() => (mesh.current.rotation.x += 0.01));
return(
<>
<mesh position={position} ref={mesh}>
<sphereBufferGeometry attach='geometry' args={[0.02,500, 500]} />
<meshStandardMaterial attach='material' color={color}/>
</mesh>
</>
);
}
export default App;https://stackoverflow.com/questions/66131246
复制相似问题