声明:本文为原创文章,转载请注明出处。
实现效果:
IK关节插件:https://download.csdn.net/download/ThreePointsHeat/12465792
工业机器油缸绑定,控制其关节运动,使用纯代码来实现不容易搞定,所以在unity商店买了一套IK插件来实现功能。
首先需要在外油缸处添加两个组件Rotation Limt Hinge 和 CCDIK。
Rotation Limt Hinge:
Axis:用来控制油缸旋转方向。
Min:油缸旋转最小值范围。
Max:油缸旋转最大值范围。(一般设置为-180 ~ 180)也就是0 ~ 360°
CCDIK:
Fix Transforrms:修复自身(不要勾选)
Target:目标对象(两根互相关联运动油缸,把另一根油缸的旋转父物体拖进去)
Bones:骨骼(把当前旋转父物体和其子物体拖进去)
当两跟相互关联运动的油缸骨骼IK都绑定好之后,就可以开始写运动逻辑代码了,代码如下:
/// <summary>
/// 车辆关节运动逻辑控制
/// </summary>
private void OnJointSport()
{
if (Input.GetKey(KeyCode.Alpha1) || Input.GetKey(KeyCode.Keypad1))
{
if (Input.GetKey(KeyCode.PageUp))
{
temp_1 = Joints[0].localEulerAngles;
temp_1 = EulerTo180(temp_1, "z");
if (temp_1.z < 38)
{
temp_1 += Vector3.forward * Time.fixedDeltaTime * Speed;
}
Joints[0].localEulerAngles = temp_1;
}
else if (Input.GetKey(KeyCode.PageDown))
{
temp_1 = Joints[0].localEulerAngles;
temp_1 = EulerTo180(temp_1, "z");
if (temp_1.z > 0)
{
temp_1 -= Vector3.forward * Time.fixedDeltaTime * Speed;
}
Joints[0].localEulerAngles = temp_1;
}
}
}
/// <summary>
/// 控制油缸运动逻辑
/// </summary>
/// <param name="e">油缸旋转</param>
/// <param name="dir">旋转轴</param>
/// <returns></returns>
private Vector3 EulerTo180(Vector3 e, string dir)
{
switch (dir)
{
case "x":
if (e.x > 180f)
{
e -= Vector3.right * 360f;
}
else if (e.x < -180f)
{
e += Vector3.right * 360f;
}
break;
case "y":
if (e.y > 180f)
{
e -= Vector3.up * 360f;
}
else if (e.y < -180f)
{
e += Vector3.up * 360f;
}
break;
case "z":
if (e.z > 180f)
{
e -= Vector3.forward * 360f;
}
else if (e.z < -180f)
{
e += Vector3.forward * 360f;
}
break;
default: break;
}
return e;
}
如有疑问,请私信。