Back









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

Featured Snippets


File name: ChatGui.cs Copy
58     public void Start()
59     {
60         DontDestroyOnLoad(this.gameObject);
61         Application.runInBackground = true; // this must run in background or it will drop connection if not focussed.
62
63         if (string.IsNullOrEmpty(this.UserName))
64         {
65             this.UserName = "user" + Environment.TickCount%99; //made-up username
66         }
67
68         chatClient = new ChatClient(this);
69         chatClient.Connect(ChatAppId, "1.0", this.UserName, null);
70
71         if (this.AlignBottom)
72         {
73             this.GuiRect.y = Screen.height - this.GuiRect.height;
74         }
75         if (this.FullScreen)
76         {
77             this.GuiRect.x = 0;
78             this.GuiRect.y = 0;
79             this.GuiRect.width = Screen.width;
80             this.GuiRect.height = Screen.height;
81         }
82
83         Debug.Log(this.UserName);
84     }
File name: GUICustomAuth.cs Copy
81     void OnGUI()
82     {
83         if (PhotonNetwork.connected)
84         {
85             GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
86             return;
87         }
88
89
90         GUILayout.BeginArea(GuiRect);
91         switch (guiState)
92         {
93             case GuiState.AuthFailed:
94                 GUILayout.Label("Authentication Failed");
95
96                 GUILayout.Space(10);
97
98                 GUILayout.Label("Error message:\n'" + this.authDebugMessage + "'");
99
100                 GUILayout.Space(10);
101
102                 GUILayout.Label("For this demo set the Authentication URL in the Dashboard to:\nhttp://photon.webscript.io/auth-demo-equals");
103                 GUILayout.Label("That authentication-service has no user-database. It confirms any user if 'name equals password'.");
104                 GUILayout.Label("The error message comes from that service and can be customized.");
105
106                 GUILayout.Space(10);
107
108                 GUILayout.BeginHorizontal();
109                 if (GUILayout.Button("Back"))
110                 {
111                     SetStateAuthInput();
112                 }
113                 if (GUILayout.Button("Help"))
114                 {
115                     SetStateAuthHelp();
116                 }
117                 GUILayout.EndHorizontal();
118                 break;
119
120             case GuiState.AuthHelp:
121
122                 GUILayout.Label("By default, any player can connect to Photon.\n'Custom Authentication' can be enabled to reject players without valid user-account.");
123
124                 GUILayout.Label("The actual authentication must be done by a web-service which you host and customize. Example sourcecode for these services is available on the docs page.");
125
126                 GUILayout.Label("For this demo set the Authentication URL in the Dashboard to:\nhttp://photon.webscript.io/auth-demo-equals");
127                 GUILayout.Label("That authentication-service has no user-database. It confirms any user if 'name equals password'.");
128
129                 GUILayout.Space(10);
130                 if (GUILayout.Button("Configure Authentication (Dashboard)"))
131                 {
132                     Application.OpenURL("https://cloud.exitgames.com/dashboard");
133                 }
134                 if (GUILayout.Button("Authentication Docs"))
135                 {
136                     Application.OpenURL("https://doc.exitgames.com/en/pun/current/tutorials/pun-and-facebook-custom-authentication");
137                 }
138
139
140                 GUILayout.Space(10);
141                 if (GUILayout.Button("Back to input"))
142                 {
143                     SetStateAuthInput();
144                 }
145                 break;
146
147             case GuiState.AuthInput:
148
149                 GUILayout.Label("Authenticate yourself");
150
151                 GUILayout.BeginHorizontal();
152                 this.authName = GUILayout.TextField(this.authName, GUILayout.Width(Screen.width/4 - 5));
153                 GUILayout.FlexibleSpace();
154                 this.authToken = GUILayout.TextField(this.authToken, GUILayout.Width(Screen.width/4 - 5));
155                 GUILayout.EndHorizontal();
156
157
158                 if (GUILayout.Button("Authenticate"))
159                 {
160                     PhotonNetwork.AuthValues = new AuthenticationValues();
161                     PhotonNetwork.AuthValues.SetAuthParameters(this.authName, this.authToken);
162                     PhotonNetwork.ConnectUsingSettings("1.0");
163                 }
164
165                 GUILayout.Space(10);
166
167                 if (GUILayout.Button("Help", GUILayout.Width(100)))
168                 {
169                     SetStateAuthHelp();
170                 }
171
172                 break;
173         }
174
175         GUILayout.EndArea();
176     }
File name: PickupCamera.cs Copy
94     void Apply( Transform dummyTarget, Vector3 dummyCenter )
95     {
96         // Early out if we don't have a target
97         if( !controller )
98             return;
99
100         Vector3 targetCenter = _target.position + centerOffset;
101         Vector3 targetHead = _target.position + headOffset;
102
103         // DebugDrawStuff();
104
105         // Calculate the current & target rotation angles
106         float originalTargetAngle = _target.eulerAngles.y;
107         float currentAngle = cameraTransform.eulerAngles.y;
108
109         // Adjust real target angle when camera is locked
110         float targetAngle = originalTargetAngle;
111
112         // When pressing Fire2 (alt) the camera will snap to the target direction real quick.
113         // It will stop snapping when it reaches the target
114         if( Input.GetButton( "Fire2" ) )
115             snap = true;
116
117         if( snap )
118         {
119             // We are close to the target, so we can stop snapping now!
120             if( AngleDistance( currentAngle, originalTargetAngle ) < 3.0f )
121                 snap = false;
122
123             currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, snapSmoothLag, snapMaxSpeed );
124         }
125         // Normal camera motion
126         else
127         {
128             if( controller.GetLockCameraTimer() < lockCameraTimeout )
129             {
130                 targetAngle = currentAngle;
131             }
132
133             // Lock the camera when moving backwards!
134             // * It is really confusing to do 180 degree spins when turning around.
135             if( AngleDistance( currentAngle, targetAngle ) > 160 && controller.IsMovingBackwards() )
136                 targetAngle += 180;
137
138             currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, angularSmoothLag, angularMaxSpeed );
139         }
140
141
142         // When jumping don't move camera upwards but only down!
143         if( controller.IsJumping() )
144         {
145             // We'd be moving the camera upwards, do that only if it's really high
146             float newTargetHeight = targetCenter.y + height;
147             if( newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5 )
148                 targetHeight = targetCenter.y + height;
149         }
150         // When walking always update the target height
151         else
152         {
153             targetHeight = targetCenter.y + height;
154         }
155
156         // Damp the height
157         float currentHeight = cameraTransform.position.y;
158         currentHeight = Mathf.SmoothDamp( currentHeight, targetHeight, ref heightVelocity, heightSmoothLag );
159
160         // Convert the angle into a rotation, by which we then reposition the camera
161         Quaternion currentRotation = Quaternion.Euler( 0, currentAngle, 0 );
162
163         // Set the position of the camera on the x-z plane to:
164         // distance meters behind the target
165         cameraTransform.position = targetCenter;
166         cameraTransform.position += currentRotation * Vector3.back * distance;
167
168         // Set the height of the camera
169         cameraTransform.position = new Vector3( cameraTransform.position.x, currentHeight, cameraTransform.position.z );
170
171         // Always look at the target
172         SetUpRotation( targetCenter, targetHead );
173     }
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
30     void Update()
31     {
32         if( m_PhotonView.isMine == true )
33         {
34             ResetSpeedValues();
35
36             UpdateRotateMovement();
37
38             UpdateForwardMovement();
39             UpdateBackwardMovement();
40             UpdateStrafeMovement();
41
42             MoveCharacterController();
43             ApplyGravityToCharacterController();
44
45             ApplySynchronizedValues();
46         }
47
48         UpdateAnimation();
49     }
File name: RPGMovement.cs Copy
114     void UpdateBackwardMovement()
115     {
116         if( Input.GetKey( KeyCode.S ) == true )
117         {
118             m_CurrentMovement = -transform.forward * BackwardSpeed;
119         }
120     }
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: ThirdPersonCamera.cs Copy
86     void Apply( Transform dummyTarget, Vector3 dummyCenter )
87     {
88         // Early out if we don't have a target
89         if( !controller )
90             return;
91
92         Vector3 targetCenter = _target.position + centerOffset;
93         Vector3 targetHead = _target.position + headOffset;
94
95         // DebugDrawStuff();
96
97         // Calculate the current & target rotation angles
98         float originalTargetAngle = _target.eulerAngles.y;
99         float currentAngle = cameraTransform.eulerAngles.y;
100
101         // Adjust real target angle when camera is locked
102         float targetAngle = originalTargetAngle;
103
104         // When pressing Fire2 (alt) the camera will snap to the target direction real quick.
105         // It will stop snapping when it reaches the target
106         if( Input.GetButton( "Fire2" ) )
107             snap = true;
108
109         if( snap )
110         {
111             // We are close to the target, so we can stop snapping now!
112             if( AngleDistance( currentAngle, originalTargetAngle ) < 3.0f )
113                 snap = false;
114
115             currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, snapSmoothLag, snapMaxSpeed );
116         }
117         // Normal camera motion
118         else
119         {
120             if( controller.GetLockCameraTimer() < lockCameraTimeout )
121             {
122                 targetAngle = currentAngle;
123             }
124
125             // Lock the camera when moving backwards!
126             // * It is really confusing to do 180 degree spins when turning around.
127             if( AngleDistance( currentAngle, targetAngle ) > 160 && controller.IsMovingBackwards() )
128                 targetAngle += 180;
129
130             currentAngle = Mathf.SmoothDampAngle( currentAngle, targetAngle, ref angleVelocity, angularSmoothLag, angularMaxSpeed );
131         }
132
133
134         // When jumping don't move camera upwards but only down!
135         if( controller.IsJumping() )
136         {
137             // We'd be moving the camera upwards, do that only if it's really high
138             float newTargetHeight = targetCenter.y + height;
139             if( newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5 )
140                 targetHeight = targetCenter.y + height;
141         }
142         // When walking always update the target height
143         else
144         {
145             targetHeight = targetCenter.y + height;
146         }
147
148         // Damp the height
149         float currentHeight = cameraTransform.position.y;
150         currentHeight = Mathf.SmoothDamp( currentHeight, targetHeight, ref heightVelocity, heightSmoothLag );
151
152         // Convert the angle into a rotation, by which we then reposition the camera
153         Quaternion currentRotation = Quaternion.Euler( 0, currentAngle, 0 );
154
155         // Set the position of the camera on the x-z plane to:
156         // distance meters behind the target
157         cameraTransform.position = targetCenter;
158         cameraTransform.position += currentRotation * Vector3.back * distance;
159
160         // Set the height of the camera
161         cameraTransform.position = new Vector3( cameraTransform.position.x, currentHeight, cameraTransform.position.z );
162
163         // Always look at the target
164         SetUpRotation( targetCenter, targetHead );
165     }
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     }
File name: ThirdPersonController.cs Copy
446     public bool IsMovingBackwards()
447     {
448         return movingBack;
449     }

Download file with original file name:Back

Back 233 lượt xem

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