对RigidBody进行驱动的方法有好几种,一个是使用RigidBody.AddForce和AddTorque这类方法,一个是直接设置速度verlocity和angularVelocity,最后一个是是使用RigidBody.MovePosition和MoveRotation来设置位置和旋转,这个对位置和旋转的设置是会考虑碰撞的,就是设定刚体到某个位置,其实就是尽可能到那个位置,但是如果有障碍物其实也到不了,旋转也一样,如果碰到障碍物其实也转不到设定的角度。但很多时候这恰恰是我们希望的效果。目前感觉使用最后这种是最好控制的。使用方法举例如下:
首先是MovePosition
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Rigidbody rb;
void Awake()
{
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
floor.transform.localScale = new Vector3(6.0f, 1.0f, 6.0f);
floor.transform.position = new Vector3(0.0f, -0.5f, 0.0f);
Material matColor = new Material(Shader.Find("Standard"));
matColor.color = new Color32(32, 32, 128, 255);
floor.GetComponent<Renderer>().material = matColor;
transform.position = new Vector3(-3.0f, 0.0f, 0.0f);
Camera.main.transform.position = new Vector3(6.0f, 4.0f, 6.0f);
Camera.main.transform.localEulerAngles = new Vector3(26.0f, -135.0f, 0.0f);
}
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
void FixedUpdate()
{
if (transform.position.x > 3.0f)
{
transform.position = new Vector3(-3.0f, 0.0f, 0.0f);
}
rb.MovePosition(transform.position + transform.right * Time.fixedDeltaTime);
}
}
其次是MoveRotation
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
Rigidbody m_Rigidbody;
Vector3 m_EulerAngleVelocity;
void Start()
{
m_EulerAngleVelocity = new Vector3(0, 100, 0);
m_Rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Quaternion deltaRotation = Quaternion.Euler(m_EulerAngleVelocity * Time.fixedDeltaTime);
m_Rigidbody.MoveRotation(m_Rigidbody.rotation * deltaRotation);
}
}