目的:導入機械臂的fbx模型,利用C#編寫腳本實現機械臂的自主運動
步驟
1.在 Unity 中,右鍵點擊 “Assets” 文件夾,選擇 “Create” -> “C# Script” 來創建一個新的 C# 腳本命名為 “ArmController”。
2.雙擊打開腳本,編寫代碼來控制機械臂的運動。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ArmController : MonoBehaviour
{// 關節引用public Transform A1;public Transform A2;public Transform A3;public Transform A4;public Transform A5;public Transform A6;// 旋轉速度(度/秒)public float A1Speed = 30f;public float A2Speed = 30f;public float A3Speed = 30f;public float A4Speed = 30f;public float A5Speed = 30f;public float A6Speed = 30f;// 每個關節的旋轉方向(1為正方向,-1為反方向)private int A1Direction = 1;private int A2Direction = 1;private int A3Direction = 1;private int A4Direction = 1;private int A5Direction = 1;private int A6Direction = 1;// 每個關節獨立的角度范圍設置[Header("A1關節角度范圍")]public float A1MinAngle = 0f;public float A1MaxAngle = 150f;[Header("A2關節角度范圍")]public float A2MinAngle = 0f;public float A2MaxAngle = 150f;[Header("A3關節角度范圍")]public float A3MinAngle = 0f;public float A3MaxAngle = 150f;[Header("A4關節角度范圍")]public float A4MinAngle = 0f;public float A4MaxAngle = 150f;[Header("A5關節角度范圍")]public float A5MinAngle = 0f;public float A5MaxAngle = 150f;[Header("A6關節角度范圍")]public float A6MinAngle = 0f;public float A6MaxAngle = 150f;void Update(){RotateJoint(A1, ref A1Direction, A1Speed, Vector3.up, A1MinAngle, A1MaxAngle);RotateJoint(A2, ref A2Direction, A2Speed, Vector3.forward, A2MinAngle, A2MaxAngle);RotateJoint(A3, ref A3Direction, A3Speed, Vector3.forward, A3MinAngle, A3MaxAngle);RotateJoint(A4, ref A4Direction, A4Speed, Vector3.right, A4MinAngle, A4MaxAngle);RotateJoint(A5, ref A5Direction, A5Speed, Vector3.forward, A5MinAngle, A5MaxAngle);RotateJoint(A6, ref A6Direction, A6Speed, Vector3.right, A6MinAngle, A6MaxAngle);}// 關節旋轉控制函數,帶獨立角度范圍參數private void RotateJoint(Transform joint, ref int direction, float speed, Vector3 axis, float minAngle, float maxAngle){if (joint == null) return;// 獲取當前關節在指定軸上的旋轉角度float currentAngle = Mathf.Repeat(joint.localEulerAngles[GetAxisIndex(axis)], 360f);// 處理角度超過180度的情況(轉換為負角度便于判斷)if (currentAngle > 180f){currentAngle -= 360f;}// 檢查是否達到角度限制,需要反轉方向if (currentAngle >= maxAngle){direction = -1;}else if (currentAngle <= minAngle){direction = 1;}// 應用旋轉joint.Rotate(axis, direction * speed * Time.deltaTime);}// 獲取軸對應的索引(x=0, y=1, z=2)private int GetAxisIndex(Vector3 axis){if (axis == Vector3.right) return 0; // x軸if (axis == Vector3.up) return 1; // y軸if (axis == Vector3.forward) return 2; // z軸return 0;}
}
3.將編寫好的腳本ArmController
掛載到機械臂的根節點 GameObject 上(即拖到整個機械臂模型的最上層父節點)。
4.在 Unity 編輯器中,選中掛載腳本的機械臂根節點,在 “Inspector” 面板中設置腳本組件的各個公共變量。
5.點擊 Unity 編輯器上方的 “Play” 按鈕,運行場景進行自主運動。