----更新(2015-7-1):
也可以用itween來移動跳台。
----
例如人物跳到往復運動的移動跳台上后應隨跳台運動。
要實現這個效果有兩個思路,一是用運動學一是用動力學。
用動力學實現就是通過設置人物collider和跳台collider摩擦屬性(使用自已創建的physic material替換collider中原來的material,然后設置摩擦屬性)。這個方法我沒試出來,下面只說使用運動學方法實現:
1,創建一個box作為移動跳台,用unity里內置的Animation Curves調個左右往復運動的動畫。
2,為移動跳台添加Rigidbody並勾選Is Kinematic。這樣,移動跳台本身就不再接受動力學作用了,但是它會對其它物體產生動力學作用。(While the Rigidbody is marked isKinematic, it will not be affected by collisions, forces, or any other part of physX. This means that you will have to control the object by manipulating the Transform component directly. Kinematic Rigidbodies will affect other objects, but they themselves will not be affected by physics. 引自:http://docs.unity3d.com/Manual/class-Rigidbody.html)
3,在playerController腳本中實現邏輯,如果人物處於非跳起狀態且向下的raycast獲得的hitInfo。滿足hitInfo.transform.gameObject.layer==LayerMask.NameToLayer ("movingPlatform"),即player落在移動平台上,則將player的Rigidbody的水平速度設為移動跳台的水平速度。而如果不是這種情況,即player落在普通靜態地面上,則player的Rigidbody水平速度設為0。
但需要注意的是移動跳台的速度並不是hitInfo.transform.gameObject.getComponent<Rigidbody>().velocity,實際上這個速度是0,因為移動跳台是用unity自帶動畫編輯功能搞的,而不是用物理搞的,所以要獲得移動跳台的速度,需要如下做:
為移動跳台添加計算速度的腳本:
using UnityEngine; using System.Collections; public class calculateMovingPlatformVelocity : MonoBehaviour { private Vector3 m_pos; private Vector3 m_posF; public Vector3 m_velocity; // Use this for initialization void Start () { } void FixedUpdate(){ ////Debug.Log (gameObject.GetComponent<Rigidbody>().velocity);//the velocity is zero!!! so we cant use it m_posF = m_pos; m_pos = gameObject.transform.position; m_velocity = (m_pos - m_posF) / Time.fixedDeltaTime; } }
在playerController腳本中獲得此速度:hitInfo.transform.gameObject.GetComponent<calculateMovingPlatformVelocity>().m_velocity。
另外要將player的body、foot以及movingPlatform的摩擦屬性設為0和Minimum。
4,至此差不多搞定了,唯一一個問題就是發現人物跳上移動跳台后跳台的運動會變得不那么流暢(略微卡頓),而且可以看出並不是性能問題導致的。后來我嘗試對跳台的Animator作如下設置:Animator->Update Mode由Normal改為Animate Physics,卡頓就不再發生了,至此達到了理想效果。
注:Update Mode取Animate Physics的含義:http://answers.unity3d.com/questions/587115/how-can-i-use-animate-physics-in-a-project.html