Clamp









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

Featured Snippets


File name: PickupCamera.cs Copy
198     void SetUpRotation( Vector3 centerPos, Vector3 headPos )
199     {
200         // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
201         // * When jumping up and down we don't want to center the guy in screen space.
202         // This is important to give a feel for how high you jump and avoiding large camera movements.
203         //
204         // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
205         //
206         // So here is what we will do:
207         //
208         // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
209         // 2. When grounded we make him be centered
210         // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
211         // 4. When landing we smoothly interpolate towards centering him on screen
212         Vector3 cameraPos = cameraTransform.position;
213         Vector3 offsetToCenter = centerPos - cameraPos;
214
215         // Generate base rotation only around y-axis
216         Quaternion yRotation = Quaternion.LookRotation( new Vector3( offsetToCenter.x, 0, offsetToCenter.z ) );
217
218         Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height;
219         cameraTransform.rotation = yRotation * Quaternion.LookRotation( relativeOffset );
220
221         // Calculate the projected center position and top position in world space
222         Ray centerRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, 0.5f, 1 ) );
223         Ray topRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, clampHeadPositionScreenSpace, 1 ) );
224
225         Vector3 centerRayPos = centerRay.GetPoint( distance );
226         Vector3 topRayPos = topRay.GetPoint( distance );
227
228         float centerToTopAngle = Vector3.Angle( centerRay.direction, topRay.direction );
229
230         float heightToAngle = centerToTopAngle / ( centerRayPos.y - topRayPos.y );
231
232         float extraLookAngle = heightToAngle * ( centerRayPos.y - centerPos.y );
233         if( extraLookAngle < centerToTopAngle )
234         {
235             extraLookAngle = 0;
236         }
237         else
238         {
239             extraLookAngle = extraLookAngle - centerToTopAngle;
240             cameraTransform.rotation *= Quaternion.Euler( -extraLookAngle, 0, 0 );
241         }
242     }
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: RPGCamera.cs Copy
20     void Start()
21     {
22         m_CameraTransform = transform.GetChild( 0 );
23         m_LocalForwardVector = m_CameraTransform.forward;
24
25         m_Distance = -m_CameraTransform.localPosition.z / m_CameraTransform.forward.z;
26         m_Distance = Mathf.Clamp( m_Distance, MinimumDistance, MaximumDistance );
27         m_LookAtPoint = m_CameraTransform.localPosition + m_LocalForwardVector * m_Distance;
28     }
File name: RPGCamera.cs Copy
38     void UpdateDistance()
39     {
40         m_Distance = Mathf.Clamp( m_Distance - Input.GetAxis( "Mouse ScrollWheel" ) * ScrollModifier, MinimumDistance, MaximumDistance );
41     }
File name: ThirdPersonCamera.cs Copy
190     void SetUpRotation( Vector3 centerPos, Vector3 headPos )
191     {
192         // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
193         // * When jumping up and down we don't want to center the guy in screen space.
194         // This is important to give a feel for how high you jump and avoiding large camera movements.
195         //
196         // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
197         //
198         // So here is what we will do:
199         //
200         // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
201         // 2. When grounded we make him be centered
202         // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
203         // 4. When landing we smoothly interpolate towards centering him on screen
204         Vector3 cameraPos = cameraTransform.position;
205         Vector3 offsetToCenter = centerPos - cameraPos;
206
207         // Generate base rotation only around y-axis
208         Quaternion yRotation = Quaternion.LookRotation( new Vector3( offsetToCenter.x, 0, offsetToCenter.z ) );
209
210         Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height;
211         cameraTransform.rotation = yRotation * Quaternion.LookRotation( relativeOffset );
212
213         // Calculate the projected center position and top position in world space
214         Ray centerRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, 0.5f, 1 ) );
215         Ray topRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, clampHeadPositionScreenSpace, 1 ) );
216
217         Vector3 centerRayPos = centerRay.GetPoint( distance );
218         Vector3 topRayPos = topRay.GetPoint( distance );
219
220         float centerToTopAngle = Vector3.Angle( centerRay.direction, topRay.direction );
221
222         float heightToAngle = centerToTopAngle / ( centerRayPos.y - topRayPos.y );
223
224         float extraLookAngle = heightToAngle * ( centerRayPos.y - centerPos.y );
225         if( extraLookAngle < centerToTopAngle )
226         {
227             extraLookAngle = 0;
228         }
229         else
230         {
231             extraLookAngle = extraLookAngle - centerToTopAngle;
232             cameraTransform.rotation *= Quaternion.Euler( -extraLookAngle, 0, 0 );
233         }
234     }
File name: RotateCamera.cs Copy
48  protected void Update() {
49   if (!rotate) return;
50   lookAngleY += inputManager.MouseAxis.x * horizAngleMove;
51   newRotY = Quaternion.Euler(0f,lookAngleY,0f);
52
53   lookAngleX += inputManager.MouseAxis.y * vertAngleMove;
54   lookAngleX = Mathf.Clamp(lookAngleX, -xAngleMin, xAngleMax);
55   newRotX = Quaternion.Euler(lookAngleX, pivotEulers.y, pivotEulers.z);
56
57   if (turnSmoothing > 0) {
58    pivotTransform.localRotation = Quaternion.Slerp(pivotTransform.localRotation, newRotX, turnSmoothing * Time.deltaTime);
59    transform.localRotation = Quaternion.Slerp(transform.localRotation, newRotY, turnSmoothing * Time.deltaTime);
60   } else {
61    transform.localRotation = newRotY;
62    pivotTransform.localRotation = newRotX;
63   }
64  }
File name: ZoomCamera.cs Copy
36  public void OnInputEvent(InputActionType action) {
37   switch (action) {
38    case InputActionType.ZOOM_IN:
39     fieldOfView -= sensitivity;
40     break;
41    case InputActionType.ZOOM_OUT:
42     fieldOfView += sensitivity;
43     break;
44   }
45
46   fieldOfView = Mathf.Clamp(fieldOfView,minFOV,maxFOV);
47   zoomCamera.fieldOfView = fieldOfView;
48  }
File name: Grid.cs Copy
68  public Node GetNodeAt(Vector3 pos) {
69   pos -= transform.position;
70
71   float percentRow = (pos.z / size.z) + 0.5f;
72   float percentCol = (pos.x / size.x) + 0.5f;
73   percentRow = Mathf.Clamp01(percentRow);
74   percentCol = Mathf.Clamp01(percentCol);
75   int row = Mathf.RoundToInt((rows-1) * percentRow);
76   int col = Mathf.RoundToInt((cols-1) * percentCol);
77
78   return grid[row,col];
79  }
File name: PlayerController.cs Copy
43  void PlayerMovement(){
44   if(Input.GetKey(KeyCode.LeftArrow)){
45    position.x -= speed * Time.deltaTime;
46   }else if(Input.GetKey(KeyCode.RightArrow)){
47    position.x += speed * Time.deltaTime;
48   }
49
50   position.x = Mathf.Clamp (position.x, maxLeft + 0.5f, maxRight - 0.5f);
51   transform.position = position;
52
53  }
File name: PlayerController.cs Copy
55  void TouchMovement(){
56   if(Input.touchCount > 0){
57    Touch touch = Input.GetTouch (0);
58
59    if(touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Began){
60     Vector3 fingerPos = touch.position;
61     position.x = fingerPos.x;
62     realPos = Camera.main.ScreenToWorldPoint (new Vector3(position.x, position.y ,position.z));
63     transform.position = Vector3.Lerp (transform.position, new Vector3(Mathf.Clamp(realPos.x, maxLeft + 0.5f, maxRight - 0.5f), transform.position.y, transform.position.z), Time.deltaTime * speed);
64
65    }
66
67    if (touch.phase == TouchPhase.Moved) {
68     Vector3 fingerPos = touch.position;
69     position.x = fingerPos.x;
70     realPos = Camera.main.ScreenToWorldPoint (new Vector3(position.x, position.y ,position.z));
71     transform.position = Vector3.Lerp (transform.position, new Vector3(Mathf.Clamp(realPos.x, maxLeft + 0.5f, maxRight - 0.5f), transform.position.y, transform.position.z), speed);
72    }
73
74   }
75  }

Clamp 162 lượt xem

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