Unity 物件Rigidbody自轉代碼


如何把3D Object弄成會自己旋轉呢?

首先把物件用add component 方法加上Rigidbody,之後用下面代碼新建一個cs檔案,再把新建的cs用add component 方法加進物件中。物件便會自轉了。

旋轉速度可以在Inspector中調節

代碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class myRotation : MonoBehaviour {
	
	private Vector3 origin;
	public Rigidbody Mover;
	public float speed=0.5f;
	Vector3 m_EulerAngleVelocity;
	
    void Awake() {
		Mover = GetComponent<Rigidbody>();
		origin=Mover.position;
    }
	
    void FixedUpdate() {
		m_EulerAngleVelocity = new Vector3(0, -speed,0);		
		Quaternion deltaRotation = Quaternion.Euler(m_EulerAngleVelocity);
		Mover.MoveRotation(Mover.rotation * deltaRotation);
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料