LoginSignup
mkgchk
@mkgchk (M K)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

threejsで首振り扇風機みたいな動きができない

解決したいこと

threejsで首振り扇風機みたいな動きを作りたいです。
十字のボックスをz軸で回転させて、さらにグループでy軸回転させると、
首振りにならず、ミックスした回転になります。
解決方法を教えて下さい。

発生している問題・エラー

See the Pen rotation by mkgchk (@mkgchk) on CodePen.

該当するソースコード

import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.module.min.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
	75,
	window.innerWidth / window.innerHeight,
	0.1,
	1000
);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const group = new THREE.Group();
scene.add(group);

const boxGeometry = new THREE.BoxGeometry(1.0, 3.0, 1.0);
const material = new THREE.MeshPhongMaterial({color:0x3399ff});
const box1 = new THREE.Mesh(boxGeometry,material);
group.add(box1);
const box2 = new THREE.Mesh(boxGeometry,material);
box2.rotation.z=Math.PI/2;
group.add(box2);

const directionalLight = new THREE.DirectionalLight(
      0xffffff,
      1.0
    );
directionalLight.position.set(
	1.0,
	1.0,
	1.0
);
scene.add(directionalLight);

camera.position.z = 5;

function animate() {
	requestAnimationFrame(animate);
	box1.rotation.z +=0.05;
	box2.rotation.z +=0.05;
	group.rotation.y +=0.05;
	renderer.render(scene, camera);
}

function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);
}

animate();
window.addEventListener("resize", onWindowResize, false);

自分で試したこと

十字のボックスをz軸で回転させて、さらにグループでy軸回転させる.

0

2Answer

扇風機の首振り運動なら、構造的に放物線運動を利用すると自然な動きになると思います。

+ let s = 0;
+ const swingAngle = 120; // 首振り角度
+ const swingCycle = 100; // 首振り周期

function animate() {
  requestAnimationFrame(animate);
  box1.rotation.z +=0.05;
  box2.rotation.z +=0.05;
-  group.rotation.y +=0.05;
+  box1.rotation.y = box2.rotation.y = Math.cos(s++ / swingCycle) * Math.PI / 360 * swingAngle;

  renderer.render(scene, camera);
}
1

Comments

  1. @mkgchk

    Questioner
    ありがとうございます。1行で書けて綺麗ですね。

やりたいことは、このようなイメージでしょうか?
(修正前が上で、修正後が下です。)

See the Pen rotation by yotty (@yotty) on CodePen.

boxをz軸方向にずらした状態でgroupをy軸方向に回転させると、首振り扇風機に近い動きになりました。

0

Comments

  1. @mkgchk

    Questioner
    ありがとうございます。boxをz軸方向にずらした状態だと、より首振り扇風機に近い動きになりますね。

Your answer might help someone💌