Lerp









How do I use Lerp
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: ClickAndDrag.cs Copy
11  void Update ()
12  {
13         if (!photonView.isMine)
14         {
15             return;
16         }
17
18      InputToEvent input = Camera.main.GetComponent();
19      if (input == null) return;
20         if (!following)
21         {
22             if (input.Dragging)
23             {
24                 camOnPress = this.transform.position;
25                 following = true;
26             }
27             else
28             {
29                 return;
30             }
31         }
32         else
33         {
34             if (input.Dragging)
35             {
36                 Vector3 target = camOnPress - (new Vector3(input.DragVector.x, 0, input.DragVector.y) * factor);
37                 this.transform.position = Vector3.Lerp(this.transform.position, target, Time.deltaTime*.5f);
38             }
39             else
40             {
41                 camOnPress = Vector3.zero;
42                 following = false;
43             }
44         }
45  }
File name: MoveCam.cs Copy
22     private void Update()
23     {
24         camTransform.position = Vector3.Slerp(camTransform.position, randomPos, Time.deltaTime);
25         camTransform.LookAt(lookAt);
26         if (Vector3.Distance(camTransform.position, randomPos) < 0.5f)
27         {
28             randomPos = originalPos + new Vector3(Random.Range(-2, 2), Random.Range(-2, 2), Random.Range(-1, 1));
29         }
30     }
File name: DemoMecanimGUI.cs Copy
33     public void Update()
34     {
35         FindRemoteAnimator();
36
37         m_SlideIn = Mathf.Lerp( m_SlideIn, m_IsOpen ? 1f : 0f, Time.deltaTime * 9f );
38         m_FoundPlayerSlideIn = Mathf.Lerp( m_FoundPlayerSlideIn, m_AnimatorView == null ? 0f : 1f, Time.deltaTime * 5f );
39     }
File name: PickupController.cs Copy
151     void Update()
152     {
153         if (isControllable)
154         {
155             if (Input.GetButtonDown("Jump"))
156             {
157                 lastJumpButtonTime = Time.time;
158             }
159
160             UpdateSmoothedMovementDirection();
161
162             // Apply gravity
163             // - extra power jump modifies gravity
164             // - controlledDescent mode modifies gravity
165             ApplyGravity();
166
167             // Apply jumping logic
168             ApplyJumping();
169
170
171             // Calculate actual motion
172             Vector3 movement = moveDirection * moveSpeed + new Vector3(0, verticalSpeed, 0) + inAirVelocity;
173             movement *= Time.deltaTime;
174
175             //Debug.Log(movement.x.ToString("0.000") + ":" + movement.z.ToString("0.000"));
176
177             // Move the controller
178             CharacterController controller = GetComponent();
179             collisionFlags = controller.Move(movement);
180
181         }
182
183         // PUN: if a remote position is known, we smooth-move to it (being late(r) but smoother)
184         if (this.remotePosition != Vector3.zero)
185         {
186             transform.position = Vector3.Lerp(transform.position, this.remotePosition, Time.deltaTime * this.RemoteSmoothing);
187         }
188
189         velocity = (transform.position - lastPos)*25;
190
191         // ANIMATION sector
192         if (_animation)
193         {
194             if (_characterState == PickupCharacterState.Jumping)
195             {
196                 if (!jumpingReachedApex)
197                 {
198                     _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
199                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
200                     _animation.CrossFade(jumpPoseAnimation.name);
201                 }
202                 else
203                 {
204                     _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
205                     _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
206                     _animation.CrossFade(jumpPoseAnimation.name);
207                 }
208             }
209             else
210             {
211                 if (_characterState == PickupCharacterState.Idle)
212                 {
213                     _animation.CrossFade(idleAnimation.name);
214                 }
215                 else if (_characterState == PickupCharacterState.Running)
216                 {
217                     _animation[runAnimation.name].speed = runMaxAnimationSpeed;
218                     if (this.isControllable)
219                     {
220                         _animation[runAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, runMaxAnimationSpeed);
221                     }
222                     _animation.CrossFade(runAnimation.name);
223                 }
224                 else if (_characterState == PickupCharacterState.Trotting)
225                 {
226                     _animation[walkAnimation.name].speed = trotMaxAnimationSpeed;
227                     if (this.isControllable)
228                     {
229                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, trotMaxAnimationSpeed);
230                     }
231                     _animation.CrossFade(walkAnimation.name);
232                 }
233                 else if (_characterState == PickupCharacterState.Walking)
234                 {
235                     _animation[walkAnimation.name].speed = walkMaxAnimationSpeed;
236                     if (this.isControllable)
237                     {
238                         _animation[walkAnimation.name].speed = Mathf.Clamp(velocity.magnitude, 0.0f, walkMaxAnimationSpeed);
239                     }
240                     _animation.CrossFade(walkAnimation.name);
241                 }
242
243                 if (_characterState != PickupCharacterState.Running)
244                 {
245                     _animation[runAnimation.name].time = 0.0f;
246                 }
247             }
248         }
249         // ANIMATION sector
250
251         // Set rotation to the move direction
252         if (IsGrounded())
253         {
254             // a specialty of this controller: you can disable rotation!
255             if (DoRotate)
256             {
257                 transform.rotation = Quaternion.LookRotation(moveDirection);
258             }
259         }
260         else
261         {
262             /* This causes choppy behaviour when colliding with SIDES
263              * Vector3 xzMove = velocity;
264             xzMove.y = 0;
265             if (xzMove.sqrMagnitude > 0.001f)
266             {
267                 transform.rotation = Quaternion.LookRotation(xzMove);
268             }*/
269         }
270
271         // We are in jump mode but just became grounded
272         if (IsGrounded())
273         {
274             lastGroundedTime = Time.time;
275             inAirVelocity = Vector3.zero;
276             if (jumping)
277             {
278                 jumping = false;
279                 SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
280             }
281         }
282
283         lastPos = transform.position;
284     }
File name: CubeInter.cs Copy
79     // This only runs where the component is enabled, which is only on remote peers (server/clients)
80     void Update()
81     {
82         double currentTime = PhotonNetwork.time;
83         double interpolationTime = currentTime - interpolationBackTime;
84         // We have a window of interpolationBackTime where we basically play
85         // By having interpolationBackTime the average ping, you will usually use interpolation.
86         // And only if no more data arrives we will use extrapolation
87
88         // Use interpolation
89         // Check if latest state exceeds interpolation time, if this is the case then
90         // it is too old and extrapolation should be used
91         if (m_BufferedState[0].timestamp > interpolationTime)
92         {
93     for (int i = 0; i < m_TimestampCount; i++)
94             {
95                 // Find the state which matches the interpolation time (time+0.1) or use last state
96                 if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount - 1)
97                 {
98                     // The state one slot newer (<100ms) than the best playback state
99                     State rhs = m_BufferedState[Mathf.Max(i - 1, 0)];
100                     // The best playback state (closest to 100 ms old (default time))
101                     State lhs = m_BufferedState[i];
102
103                     // Use the time between the two slots to determine if interpolation is necessary
104                     double length = rhs.timestamp - lhs.timestamp;
105                     float t = 0.0F;
106                     // As the time difference gets closer to 100 ms t gets closer to 1 in
107                     // which case rhs is only used
108                     if (length > 0.0001)
109                         t = (float)((interpolationTime - lhs.timestamp) / length);
110
111                     // if t=0 => lhs is used directly
112                     transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
113                     transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
114      return;
115                 }
116             }
117         }
118         // Use extrapolation. Here we do something really simple and just repeat the last
119         // received state. You can do clever stuff with predicting what should happen.
120         else
121         {
122             State latest = m_BufferedState[0];
123
124             transform.localPosition = Vector3.Lerp(transform.localPosition, latest.pos, Time.deltaTime * 20 );
125             transform.localRotation = latest.rot;
126         }
127     }
File name: CubeLerp.cs Copy
61     public void Update()
62     {
63         // We get 10 updates per sec. sometimes a few less or one or two more, depending on variation of lag.
64         // Due to that we want to reach the correct position in a little over 100ms. This way, we usually avoid a stop.
65         // Lerp() gets a fraction value between 0 and 1. This is how far we went from A to B.
66         //
67         // Our fraction variable would reach 1 in 100ms if we multiply deltaTime by 10.
68         // We want it to take a bit longer, so we multiply with 9 instead.
69
70         fraction = fraction + Time.deltaTime * 9;
71         transform.localPosition = Vector3.Lerp(onUpdatePos, latestCorrectPos, fraction); // set our pos between A and B
72     }
File name: ThirdPersonNetwork.cs Copy
52     void Update()
53     {
54         if (!photonView.isMine)
55         {
56             //Update remote player (smooth this, this looks good, at the cost of some accuracy)
57             transform.position = Vector3.Lerp(transform.position, correctPlayerPos, Time.deltaTime * 5);
58             transform.rotation = Quaternion.Lerp(transform.rotation, correctPlayerRot, Time.deltaTime * 5);
59         }
60     }
File name: NetworkCharacter.cs Copy
8     void Update()
9     {
10         if (!photonView.isMine)
11         {
12             transform.position = Vector3.Lerp(transform.position, this.correctPlayerPos, Time.deltaTime * 5);
13             transform.rotation = Quaternion.Lerp(transform.rotation, this.correctPlayerRot, Time.deltaTime * 5);
14         }
15     }
File name: PlayerDiamond.cs Copy
62     void UpdateDiamondPosition()
63     {
64         Vector3 targetPosition = Vector3.zero;
65
66         if( HeadTransform != null )
67         {
68             targetPosition = HeadTransform.position;
69         }
70
71         targetPosition.y = m_Height;
72
73         if( float.IsNaN( targetPosition.x ) == false && float.IsNaN( targetPosition.z ) == false )
74         {
75             transform.position = Vector3.Lerp( transform.position, targetPosition, Time.deltaTime * 10f );
76         }
77     }
File name: PhotonAnimatorViewEditor.cs Copy
179     private void DrawParameterInspector()
180     {
181         SerializedProperty foldoutProperty = serializedObject.FindProperty("ShowParameterInspector");
182         foldoutProperty.boolValue = PhotonGUI.ContainerHeaderFoldout("Synchronize Parameters", foldoutProperty.boolValue);
183
184         if (foldoutProperty.boolValue == false)
185         {
186             return;
187         }
188
189         float lineHeight = 20;
190         Rect containerRect = PhotonGUI.ContainerBody(GetParameterCount()*lineHeight);
191
192         for (int i = 0; i < GetParameterCount(); i++)
193         {
194             AnimatorControllerParameter parameter = null;
195
196#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6
197             parameter = this.m_Controller.GetParameter(i);
198#else
199             parameter = m_Animator.parameters[ i ];
200#endif
201
202             string defaultValue = "";
203
204             if (parameter.type == AnimatorControllerParameterType.Bool)
205             {
206                 defaultValue += parameter.defaultBool.ToString();
207             }
208             else if (parameter.type == AnimatorControllerParameterType.Float)
209             {
210                 defaultValue += parameter.defaultFloat.ToString();
211             }
212             else if (parameter.type == AnimatorControllerParameterType.Int)
213             {
214                 defaultValue += parameter.defaultInt.ToString();
215             }
216
217             if (this.m_Target.DoesParameterSynchronizeTypeExist(parameter.name) == false)
218             {
219                 this.m_Target.SetParameterSynchronized(parameter.name, (PhotonAnimatorView.ParameterType) parameter.type, PhotonAnimatorView.SynchronizeType.Disabled);
220                 EditorUtility.SetDirty(this.m_Target);
221             }
222
223             PhotonAnimatorView.SynchronizeType value = this.m_Target.GetParameterSynchronizeType(parameter.name);
224
225             Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + i*lineHeight, containerRect.width, lineHeight);
226
227             Rect labelRect = new Rect(elementRect.xMin + 5, elementRect.yMin + 2, EditorGUIUtility.labelWidth - 5, elementRect.height);
228             GUI.Label(labelRect, parameter.name + " (" + defaultValue + ")");
229
230             Rect popupRect = new Rect(elementRect.xMin + EditorGUIUtility.labelWidth, elementRect.yMin + 2, elementRect.width - EditorGUIUtility.labelWidth - 5, EditorGUIUtility.singleLineHeight);
231             value = (PhotonAnimatorView.SynchronizeType) EditorGUI.EnumPopup(popupRect, value);
232
233             if (i < GetParameterCount() - 1)
234             {
235                 Rect splitterRect = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1);
236                 PhotonGUI.DrawSplitter(splitterRect);
237             }
238
239             if (value != this.m_Target.GetParameterSynchronizeType(parameter.name))
240             {
241                 Undo.RecordObject(target, "Modify Synchronize Parameter " + parameter.name);
242                 this.m_Target.SetParameterSynchronized(parameter.name, (PhotonAnimatorView.ParameterType) parameter.type, value);
243
244                 EditorUtility.SetDirty(this.m_Target);
245             }
246         }
247     }

Download file with original file name:Lerp

Lerp 161 lượt xem

Gõ tìm kiếm nhanh...