Float









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

Featured Snippets


File name: frmCapNhat.cs Copy
367         private void buton1_Click(object sender, EventArgs e)
368         {
369             float i = 50;
370             if (buton1.Text == "Thu Nhỏ")
371             {
372                 while (this.Height > 370)
373                 {
374                     i += 1f;
375                     this.Height -= (int)i;
376                     Application.DoEvents();
377                     buton1.Text = "Mở Rộng";
378                 }
379             }
380             else
381             {
382
383                 while (this.Height < 600)
384                 {
385                     i += 1f;
386                     this.Height += (int)i;
387                     Application.DoEvents();
388                     buton1.Text = "Thu Nhỏ";
389                 }
390             }
391         }
File name: ChatGui.cs Copy
103     public void OnGUI()
104     {
105         if (!this.IsVisible)
106         {
107             return;
108         }
109
110         GUI.skin.label.wordWrap = true;
111         //GUI.skin.button.richText = true; // this allows toolbar buttons to have bold/colored text. nice to indicate new msgs
112         //GUILayout.Button("lala"); // as richText, html tags could be in text
113
114
115         if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return))
116         {
117             if ("ChatInput".Equals(GUI.GetNameOfFocusedControl()))
118             {
119                 // focus on input -> submit it
120                 GuiSendsMsg();
121                 return; // showing the now modified list would result in an error. to avoid this, we just skip this single frame
122             }
123             else
124             {
125                 // assign focus to input
126                 GUI.FocusControl("ChatInput");
127             }
128         }
129
130         GUI.SetNextControlName("");
131         GUILayout.BeginArea(this.GuiRect);
132
133         GUILayout.FlexibleSpace();
134
135         if (this.chatClient.State != ChatState.ConnectedToFrontEnd)
136         {
137             GUILayout.Label("Not in chat yet.");
138         }
139         else
140         {
141             List channels = new List(this.chatClient.PublicChannels.Keys); // this could be cached
142             int countOfPublicChannels = channels.Count;
143             channels.AddRange(this.chatClient.PrivateChannels.Keys);
144
145             if (channels.Count > 0)
146             {
147                 int previouslySelectedChannelIndex = this.selectedChannelIndex;
148                 int channelIndex = channels.IndexOf(this.selectedChannelName);
149                 this.selectedChannelIndex = (channelIndex >= 0) ? channelIndex : 0;
150
151                 this.selectedChannelIndex = GUILayout.Toolbar(this.selectedChannelIndex, channels.ToArray(), GUILayout.ExpandWidth(false));
152                 this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
153
154                 this.doingPrivateChat = (this.selectedChannelIndex >= countOfPublicChannels);
155                 this.selectedChannelName = channels[this.selectedChannelIndex];
156
157                 if (this.selectedChannelIndex != previouslySelectedChannelIndex)
158                 {
159                     // changed channel -> scroll down, if private: pre-fill "to" field with target user's name
160                     this.scrollPos.y = float.MaxValue;
161                     if (this.doingPrivateChat)
162                     {
163                         string[] pieces = this.selectedChannelName.Split(new char[] {':'}, 3);
164                         this.userIdInput = pieces[1];
165                     }
166                 }
167
168                 GUILayout.Label(ChatGui.WelcomeText);
169
170                 if (this.chatClient.TryGetChannel(selectedChannelName, this.doingPrivateChat, out this.selectedChannel))
171                 {
172                     for (int i = 0; i < this.selectedChannel.Messages.Count; i++)
173                     {
174                         string sender = this.selectedChannel.Senders[i];
175                         object message = this.selectedChannel.Messages[i];
176                         GUILayout.Label(string.Format("{0}: {1}", sender, message));
177                     }
178                 }
179
180                 GUILayout.EndScrollView();
181             }
182         }
183
184
185         GUILayout.BeginHorizontal();
186         if (doingPrivateChat)
187         {
188             GUILayout.Label("to:", GUILayout.ExpandWidth(false));
189             GUI.SetNextControlName("WhisperTo");
190             this.userIdInput = GUILayout.TextField(this.userIdInput, GUILayout.MinWidth(100), GUILayout.ExpandWidth(false));
191             string focussed = GUI.GetNameOfFocusedControl();
192             if (focussed.Equals("WhisperTo"))
193             {
194                 if (this.userIdInput.Equals("username"))
195                 {
196                     this.userIdInput = "";
197                 }
198             }
199             else if (string.IsNullOrEmpty(this.userIdInput))
200             {
201                 this.userIdInput = "username";
202             }
203
204         }
205         GUI.SetNextControlName("ChatInput");
206         inputLine = GUILayout.TextField(inputLine);
207         if (GUILayout.Button("Send", GUILayout.ExpandWidth(false)))
208         {
209             GuiSendsMsg();
210         }
211         GUILayout.EndHorizontal();
212         GUILayout.EndArea();
213     }
File name: ChatGui.cs Copy
334     public void OnGetMessages(string channelName, string[] senders, object[] messages)
335     {
336         if (channelName.Equals(this.selectedChannelName))
337         {
338             this.scrollPos.y = float.MaxValue;
339         }
340     }
File name: BallControl.cs Copy
10  void GoBall() {
11   float rand = Random.Range (0, 2);
12   if (rand < 1) {
13    rb2d.AddForce (new Vector2 (20, -15));
14   } else {
15    rb2d.AddForce (new Vector2 (-20, -15));
16   }
17  }
File name: DemoMecanimGUI.cs Copy
61     public void OnGUI()
62     {
63         GUI.skin = Skin;
64
65         string[] synchronizeTypeContent = new string[] { "Disabled", "Discrete", "Continuous" };
66
67         GUILayout.BeginArea( new Rect( Screen.width - 200 * m_FoundPlayerSlideIn - 400 * m_SlideIn, 0, 600, Screen.height ), GUI.skin.box );
68         {
69             GUILayout.Label( "Mecanim Demo", GUI.skin.customStyles[ 0 ] );
70
71             GUI.color = Color.white;
72             string label = "Settings";
73
74             if( m_IsOpen == true )
75             {
76                 label = "Close";
77             }
78
79             if( GUILayout.Button( label, GUILayout.Width( 110 ) ) )
80             {
81                 m_IsOpen = !m_IsOpen;
82             }
83
84             string parameters = "";
85
86             if( m_AnimatorView != null )
87             {
88                 parameters += "Send Values:\n";
89
90                 for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i )
91                 {
92                     PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ];
93
94                     try
95                     {
96                         switch( parameter.Type )
97                         {
98                         case PhotonAnimatorView.ParameterType.Bool:
99                             parameters += parameter.Name + " (" + ( m_AnimatorView.GetComponent().GetBool( parameter.Name ) ? "True" : "False" ) + ")\n";
100                             break;
101                         case PhotonAnimatorView.ParameterType.Int:
102                             parameters += parameter.Name + " (" + m_AnimatorView.GetComponent().GetInteger( parameter.Name ) + ")\n";
103                             break;
104                         case PhotonAnimatorView.ParameterType.Float:
105                             parameters += parameter.Name + " (" + m_AnimatorView.GetComponent().GetFloat( parameter.Name ).ToString( "0.00" ) + ")\n";
106                             break;
107                         }
108                     }
109                     catch
110                     {
111                         Debug.Log( "derrrr for " + parameter.Name );
112                     }
113                 }
114             }
115
116             if( m_RemoteAnimator != null )
117             {
118                 parameters += "\nReceived Values:\n";
119
120                 for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i )
121                 {
122                     PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ];
123
124                     try
125                     {
126                         switch( parameter.Type )
127                         {
128                         case PhotonAnimatorView.ParameterType.Bool:
129                             parameters += parameter.Name + " (" + ( m_RemoteAnimator.GetBool( parameter.Name ) ? "True" : "False" ) + ")\n";
130                             break;
131                         case PhotonAnimatorView.ParameterType.Int:
132                             parameters += parameter.Name + " (" + m_RemoteAnimator.GetInteger( parameter.Name ) + ")\n";
133                             break;
134                         case PhotonAnimatorView.ParameterType.Float:
135                             parameters += parameter.Name + " (" + m_RemoteAnimator.GetFloat( parameter.Name ).ToString( "0.00" ) + ")\n";
136                             break;
137                         }
138                     }
139                     catch
140                     {
141                         Debug.Log( "derrrr for " + parameter.Name );
142                     }
143                 }
144             }
145
146             GUIStyle style = new GUIStyle( GUI.skin.label );
147             style.alignment = TextAnchor.UpperLeft;
148
149             GUI.color = new Color( 1f, 1f, 1f, 1 - m_SlideIn );
150             GUI.Label( new Rect( 10, 100, 600, Screen.height ), parameters, style );
151
152             if( m_AnimatorView != null )
153             {
154                 GUI.color = new Color( 1f, 1f, 1f, m_SlideIn );
155
156                 GUILayout.Space( 20 );
157                 GUILayout.Label( "Synchronize Parameters" );
158
159                 for( int i = 0; i < m_AnimatorView.GetSynchronizedParameters().Count; ++i )
160                 {
161                     GUILayout.BeginHorizontal();
162                     {
163                         PhotonAnimatorView.SynchronizedParameter parameter = m_AnimatorView.GetSynchronizedParameters()[ i ];
164
165                         GUILayout.Label( parameter.Name, GUILayout.Width( 100 ), GUILayout.Height( 36 ) );
166
167                         int selectedValue = (int)parameter.SynchronizeType;
168                         int newValue = GUILayout.Toolbar( selectedValue, synchronizeTypeContent );
169
170                         if( newValue != selectedValue )
171                         {
172                             m_AnimatorView.SetParameterSynchronized( parameter.Name, parameter.Type, (PhotonAnimatorView.SynchronizeType)newValue );
173                         }
174                     }
175                     GUILayout.EndHorizontal();
176                 }
177             }
178         }
179         GUILayout.EndArea();
180     }
File name: PickupCamera.cs Copy
86     float AngleDistance( float a, float b )
87     {
88         a = Mathf.Repeat( a, 360 );
89         b = Mathf.Repeat( b, 360 );
90
91         return Mathf.Abs( b - a );
92     }
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: PickupCamera.cs Copy
180     void Cut( Transform dummyTarget, Vector3 dummyCenter )
181     {
182         float oldHeightSmooth = heightSmoothLag;
183         float oldSnapMaxSpeed = snapMaxSpeed;
184         float oldSnapSmooth = snapSmoothLag;
185
186         snapMaxSpeed = 10000;
187         snapSmoothLag = 0.001f;
188         heightSmoothLag = 0.001f;
189
190         snap = true;
191         Apply( transform, Vector3.zero );
192
193         heightSmoothLag = oldHeightSmooth;
194         snapMaxSpeed = oldSnapMaxSpeed;
195         snapSmoothLag = oldSnapSmooth;
196     }
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
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     }

Download file with original file name:Float

Float 117 lượt xem

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