要让一个描点的控件动画移动到一个Position,可以用TweenPosition,但是这个只能用在Position是固定的情况下,而且不能根据分辨率适配来进行移动。以NGUI自带的示例场景"Example 1 - Anchors"为例,假设要让"Left"移动到"Top Right",且不管任意分辨率都需要达到这个效果。这里的方法是修改TweenPosition代码,让其支持传入目标的Transform,而这个目标即是也被描点的控件。
打开TweenPosition.cs,添加如下代码:
1 2 3 4 5 6 7 |
public Transform sourceFrom; public Transform targetTo; static public TweenPosition Begin(GameObject go, float duration, Transform targetTo) { return Begin(go, duration, go.transform.parent.InverseTransformPoint(targetTo.position)); } |
修改OnUpdate函数为如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
protected override void OnUpdate (float factor, bool isFinished) { if (sourceFrom != null) { from = cachedTransform.parent.InverseTransformPoint(sourceFrom.position); sourceFrom = null; } if (targetTo != null) { to = cachedTransform.parent.InverseTransformPoint(targetTo.position); targetTo = null; } value = from * (1f - factor) + to * factor; } |
打开TweenPositionEditor.cs,修改OnInspectorGUI函数为如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class TweenPositionEditor : UITweenerEditor { public override void OnInspectorGUI () { GUILayout.Space(6f); NGUIEditorTools.SetLabelWidth(120f); TweenPosition tw = target as TweenPosition; GUI.changed = false; Vector3 from = EditorGUILayout.Vector3Field("From", tw.from); Transform sourceFrom = EditorGUILayout.ObjectField("Or From", tw.sourceFrom, typeof(Transform), true) as Transform; Vector3 to = EditorGUILayout.Vector3Field("To", tw.to); Transform targetTo = EditorGUILayout.ObjectField("Or To", tw.targetTo, typeof(Transform), true) as Transform; if (GUI.changed) { NGUIEditorTools.RegisterUndo("Tween Change", tw); tw.from = from; tw.to = to; tw.sourceFrom = sourceFrom; tw.targetTo = targetTo; NGUITools.SetDirty(tw); } DrawCommonProperties(); } } |
现在在检视器可以看到如下配置:
设置其"Or From"和"Or To",然后运行,即可看到位移动画,如下所示:
平时可以使用UIPlayTween来控制控件的动画播放,但是其仅支持点击、选中等等需要交互的动作才行,这里为其加入开启时就可以自动播放动画。打开AnimationOrTween.cs,为枚举Trigger增加一个枚举值,如下:
1 2 3 4 5 6 |
public enum Trigger { OnClick, …… OnEnableTrue, } |
打开UIPlayTween.cs,在其OnEnable函数最后,添加如下代码:
1 2 3 4 5 6 7 8 9 |
void OnEnable () { …… if (trigger == Trigger.OnEnableTrue) { Play(true); } } |
这样UIPlayTween就能在开启时,直接播放动画了。