Direction
How do I use Direction
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: JumpAndRunMovement.cs
Copy
22 void Update()
23 {
24 UpdateIsGrounded();
25 UpdateIsRunning();
26 UpdateFacingDirection();
27 }
File name: JumpAndRunMovement.cs
Copy
40 void UpdateFacingDirection()
41 {
42 if( m_Body.velocity.x > 0.2f )
43 {
44 transform.localScale = new Vector3( 1, 1, 1 );
45 }
46 else if( m_Body.velocity.x < -0.2f )
47 {
48 transform.localScale = new Vector3( -1, 1, 1 );
49 }
50 }
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
73 // Are we jumping? (Initiated with jump button and not grounded yet)
77 // Are we moving backwards (This locks the camera to not do a 180 degree spin)
81 // When did the user start walking (Used for going into trot after a while)
87 // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
101 void Awake()
102 {
103 // PUN: automatically determine isControllable, if this GO has a PhotonView
104 PhotonView pv = this.gameObject.GetComponent
105 if (pv != null)
106 {
107 isControllable = pv.isMine;
108
109 // The pickup demo assigns this GameObject as the PhotonPlayer.TagObject. This way, we can access this character (controller, position, etc) easily
110 if (this.AssignAsTagObject)
111 {
112 pv.owner.TagObject = this.gameObject;
113 }
114
115 // please note: we change this setting on ANY PickupController if "DoRotate" is off. not only locally when it's "our" GameObject!
116 if (pv.observed is Transform && !DoRotate)
117 {
118 pv.onSerializeTransformOption = OnSerializeTransform.OnlyPosition;
119 }
120 }
121
122
123 moveDirection = transform.TransformDirection(Vector3.forward);
124
125 _animation = GetComponent
126 if (!_animation)
127 Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
128
129 if (!idleAnimation)
130 {
131 _animation = null;
132 Debug.Log("No idle animation found. Turning off animations.");
133 }
134 if (!walkAnimation)
135 {
136 _animation = null;
137 Debug.Log("No walk animation found. Turning off animations.");
138 }
139 if (!runAnimation)
140 {
141 _animation = null;
142 Debug.Log("No run animation found. Turning off animations.");
143 }
144 if (!jumpPoseAnimation && canJump)
145 {
146 _animation = null;
147 Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
148 }
149 }
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: PickupController.cs
Copy
308 void UpdateSmoothedMovementDirection()
309 {
310 Transform cameraTransform = Camera.main.transform;
311 bool grounded = IsGrounded();
312
313 // Forward vector relative to the camera along the x-z plane
314 Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
315 forward.y = 0;
316 forward = forward.normalized;
317
318 // Right vector relative to the camera
319 // Always orthogonal to the forward vector
320 Vector3 right = new Vector3(forward.z, 0, -forward.x);
321
322 float v = Input.GetAxisRaw("Vertical");
323 float h = Input.GetAxisRaw("Horizontal");
324
325 // Are we moving backwards or looking backwards
326 if (v < -0.2f)
327 movingBack = true;
328 else
329 movingBack = false;
330
331 bool wasMoving = isMoving;
332 isMoving = Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f;
333
334 // Target direction relative to the camera
335 Vector3 targetDirection = h * right + v * forward;
336 // Debug.Log("targetDirection " + targetDirection);
337
338 // Grounded controls
339 if (grounded)
340 {
341 // Lock camera for short period when transitioning moving & standing still
342 lockCameraTimer += Time.deltaTime;
343 if (isMoving != wasMoving)
344 lockCameraTimer = 0.0f;
345
346 // We store speed and direction seperately,
347 // so that when the character stands still we still have a valid forward direction
348 // moveDirection is always normalized, and we only update it if there is user input.
349 if (targetDirection != Vector3.zero)
350 {
351 // If we are really slow, just snap to the target direction
352 if (moveSpeed < walkSpeed * 0.9f && grounded)
353 {
354 moveDirection = targetDirection.normalized;
355 }
356 // Otherwise smoothly turn towards it
357 else
358 {
359 moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
360
361 moveDirection = moveDirection.normalized;
362 }
363 }
364
365 // Smooth the speed based on the current target direction
366 float curSmooth = speedSmoothing * Time.deltaTime;
367
368 // Choose target speed
369 //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
370 float targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0f);
371
372 _characterState = PickupCharacterState.Idle;
373
374 // Pick speed modifier
375 if ((Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift)) && isMoving)
376 {
377 targetSpeed *= runSpeed;
378 _characterState = PickupCharacterState.Running;
379 }
380 else if (Time.time - trotAfterSeconds > walkTimeStart)
381 {
382 targetSpeed *= trotSpeed;
383 _characterState = PickupCharacterState.Trotting;
384 }
385 else if (isMoving)
386 {
387 targetSpeed *= walkSpeed;
388 _characterState = PickupCharacterState.Walking;
389 }
390
391 moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
392
393 // Reset walk time start when we slow down
394 if (moveSpeed < walkSpeed * 0.3f)
395 walkTimeStart = Time.time;
396 }
397 // In air controls
398 else
399 {
400 // Lock camera while in air
401 if (jumping)
402 lockCameraTimer = 0.0f;
403
404 if (isMoving)
405 inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
406 }
407 }
File name: RPGMovement.cs
Copy
51 void UpdateAnimation()
52 {
53 Vector3 movementVector = transform.position - m_LastPosition;
54
55 float speed = Vector3.Dot( movementVector.normalized, transform.forward );
56 float direction = Vector3.Dot( movementVector.normalized, transform.right );
57
58 if( Mathf.Abs( speed ) < 0.2f )
59 {
60 speed = 0f;
61 }
62
63 if( speed > 0.6f )
64 {
65 speed = 1f;
66 direction = 0f;
67 }
68
69 if( speed >= 0f )
70 {
71 if( Mathf.Abs( direction ) > 0.7f )
72 {
73 speed = 1f;
74 }
75 }
76
77 m_AnimatorSpeed = Mathf.MoveTowards( m_AnimatorSpeed, speed, Time.deltaTime * 5f );
78
79 m_Animator.SetFloat( "Speed", m_AnimatorSpeed );
80 m_Animator.SetFloat( "Direction", direction );
81
82 m_LastPosition = transform.position;
83 }
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: ThirdPersonController.cs
Copy
71 // Are we jumping? (Initiated with jump button and not grounded yet)
75 // Are we moving backwards (This locks the camera to not do a 180 degree spin)
79 // When did the user start walking (Used for going into trot after a while)
85 // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
92 void Awake()
93 {
94 moveDirection = transform.TransformDirection(Vector3.forward);
95
96 _animation = GetComponent
97 if (!_animation)
98 Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
99
100 /*
101 public AnimationClip idleAnimation;
102 public AnimationClip walkAnimation;
103 public AnimationClip runAnimation;
104 public AnimationClip jumpPoseAnimation;
105 */
106 if (!idleAnimation)
107 {
108 _animation = null;
109 Debug.Log("No idle animation found. Turning off animations.");
110 }
111 if (!walkAnimation)
112 {
113 _animation = null;
114 Debug.Log("No walk animation found. Turning off animations.");
115 }
116 if (!runAnimation)
117 {
118 _animation = null;
119 Debug.Log("No run animation found. Turning off animations.");
120 }
121 if (!jumpPoseAnimation && canJump)
122 {
123 _animation = null;
124 Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
125 }
126
127 }
File name: ThirdPersonController.cs
Copy
131 void UpdateSmoothedMovementDirection()
132 {
133 Transform cameraTransform = Camera.main.transform;
134 bool grounded = IsGrounded();
135
136 // Forward vector relative to the camera along the x-z plane
137 Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
138 forward.y = 0;
139 forward = forward.normalized;
140
141 // Right vector relative to the camera
142 // Always orthogonal to the forward vector
143 Vector3 right = new Vector3(forward.z, 0, -forward.x);
144
145 float v = Input.GetAxisRaw("Vertical");
146 float h = Input.GetAxisRaw("Horizontal");
147
148 // Are we moving backwards or looking backwards
149 if (v < -0.2f)
150 movingBack = true;
151 else
152 movingBack = false;
153
154 bool wasMoving = isMoving;
155 isMoving = Mathf.Abs(h) > 0.1f || Mathf.Abs(v) > 0.1f;
156
157 // Target direction relative to the camera
158 Vector3 targetDirection = h * right + v * forward;
159
160 // Grounded controls
161 if (grounded)
162 {
163 // Lock camera for short period when transitioning moving & standing still
164 lockCameraTimer += Time.deltaTime;
165 if (isMoving != wasMoving)
166 lockCameraTimer = 0.0f;
167
168 // We store speed and direction seperately,
169 // so that when the character stands still we still have a valid forward direction
170 // moveDirection is always normalized, and we only update it if there is user input.
171 if (targetDirection != Vector3.zero)
172 {
173 // If we are really slow, just snap to the target direction
174 if (moveSpeed < walkSpeed * 0.9f && grounded)
175 {
176 moveDirection = targetDirection.normalized;
177 }
178 // Otherwise smoothly turn towards it
179 else
180 {
181 moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
182
183 moveDirection = moveDirection.normalized;
184 }
185 }
186
187 // Smooth the speed based on the current target direction
188 float curSmooth = speedSmoothing * Time.deltaTime;
189
190 // Choose target speed
191 //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
192 float targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0f);
193
194 _characterState = CharacterState.Idle;
195
196 // Pick speed modifier
197 if (Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift))
198 {
199 targetSpeed *= runSpeed;
200 _characterState = CharacterState.Running;
201 }
202 else if (Time.time - trotAfterSeconds > walkTimeStart)
203 {
204 targetSpeed *= trotSpeed;
205 _characterState = CharacterState.Trotting;
206 }
207 else
208 {
209 targetSpeed *= walkSpeed;
210 _characterState = CharacterState.Walking;
211 }
212
213 moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
214
215 // Reset walk time start when we slow down
216 if (moveSpeed < walkSpeed * 0.3f)
217 walkTimeStart = Time.time;
218 }
219 // In air controls
220 else
221 {
222 // Lock camera while in air
223 if (jumping)
224 lockCameraTimer = 0.0f;
225
226 if (isMoving)
227 inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
228 }
229
230
231
232 }
Download file with original file name:Direction
Direction 100 lượt xem
Gõ tìm kiếm nhanh...