Ray









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

Featured Snippets


File name: frmThiThat.cs Copy
50         void TaoBangRandomCauHoi(DataTable BangQuestion)
51         {
52
53             try
54             {
55                 Random Rnd = new Random();
56                 ArrayList ArrQuestion = new ArrayList();
57
58                 ArrQuestion.Clear();
59                 int x, dem = 0;
60                 int SoCauTrongBangGoc = BangQuestion.Rows.Count;
61                 while (dem < SoCauNgauNhien)
62                 {
63                     x = Rnd.Next(0, SoCauTrongBangGoc);
64                     if (!ArrQuestion.Contains(x))
65                     {
66                         ArrQuestion.Add(x);
67                         dem++;
68                     }
69                 }
70                 for (int j = SoCauTrongBangGoc - 1; j >= 0; j--)
71                     if (!ArrQuestion.Contains(j))
72                         BangQuestion.Rows.RemoveAt(j);
73
74                 BangDeThi = BangQuestion;
75                 BangDeThi.Columns.Add("cauhoi,DAPAN");
76
77             }
78             catch (Exception ex)
79             { MessageBox.Show(ex.Message); }
80
81         }
File name: frmThiThat.cs Copy
82         void TaoBangRandomCauTraLoi()
83         {
84             try
85             {
86                 SoCauHoi = BangDeThi.Rows.Count;
87                 string DapAnDung = "";
88                 string A, B, C, D;
89                 int DapAn;
90                 Random Rnd = new Random();
91                 ArrayList ArrDapAn = new ArrayList();
92                 for (int i = 0; i < SoCauHoi; i++)
93                 {
94                     A = "";
95                     B = "";
96                     C = "";
97                     D = "";
98                     DapAnDung = "";
99                     DapAn = 0;
100                     ArrDapAn.Clear();
101                     ArrDapAn.Add(2);
102                     ArrDapAn.Add(3);
103                     ArrDapAn.Add(4);
104                     ArrDapAn.Add(5);
105
106                     DapAn = Rnd.Next(ArrDapAn.Count);
107                     A = BangDeThi.Rows[i][(int)ArrDapAn[DapAn]].ToString();
108                     if ((BangDeThi.Rows[i][6].ToString().ToUpper().Contains("A") && (int)ArrDapAn[DapAn] == 2) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("B") && (int)ArrDapAn[DapAn] == 3) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("C") && (int)ArrDapAn[DapAn] == 4) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("D") && (int)ArrDapAn[DapAn] == 5))
109                         DapAnDung += "A";
110                     ArrDapAn.RemoveAt(DapAn);
111                     DapAn = Rnd.Next(ArrDapAn.Count);
112                     B = BangDeThi.Rows[i][(int)ArrDapAn[DapAn]].ToString();
113                     if ((BangDeThi.Rows[i][6].ToString().ToUpper().Contains("A") && (int)ArrDapAn[DapAn] == 2) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("B") && (int)ArrDapAn[DapAn] == 3) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("C") && (int)ArrDapAn[DapAn] == 4) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("D") && (int)ArrDapAn[DapAn] == 5))
114                         DapAnDung += "B";
115                     ArrDapAn.RemoveAt(DapAn);
116                     DapAn = Rnd.Next(ArrDapAn.Count);
117                     C = BangDeThi.Rows[i][(int)ArrDapAn[DapAn]].ToString();
118                     if ((BangDeThi.Rows[i][6].ToString().ToUpper().Contains("A") && (int)ArrDapAn[DapAn] == 2) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("B") && (int)ArrDapAn[DapAn] == 3) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("C") && (int)ArrDapAn[DapAn] == 4) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("D") && (int)ArrDapAn[DapAn] == 5))
119                         DapAnDung += "C";
120                     ArrDapAn.RemoveAt(DapAn);
121                     DapAn = Rnd.Next(ArrDapAn.Count);
122                     D = BangDeThi.Rows[i][(int)ArrDapAn[DapAn]].ToString();
123                     if ((BangDeThi.Rows[i][6].ToString().ToUpper().Contains("A") && (int)ArrDapAn[DapAn] == 2) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("B") && (int)ArrDapAn[DapAn] == 3) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("C") && (int)ArrDapAn[DapAn] == 4) || (BangDeThi.Rows[i][6].ToString().ToUpper().Contains("D") && (int)ArrDapAn[DapAn] == 5))
124                         DapAnDung += "D";
125                     BangDeThi.Rows[i][2] = A;
126                     BangDeThi.Rows[i][3] = B;
127                     BangDeThi.Rows[i][4] = C;
128                     BangDeThi.Rows[i][5] = D;
129                     BangDeThi.Rows[i][6] = DapAnDung;
130                 }
131             }
132             catch (Exception ex)
133             { MessageBox.Show(ex.Message); }
134         }
File name: JumpAndRunMovement.cs Copy
94     void UpdateIsGrounded()
95     {
96         Vector2 position = new Vector2( transform.position.x, transform.position.y );
97
98         RaycastHit2D hit = Physics2D.Raycast( position, -Vector2.up, 0.1f, 1 << LayerMask.NameToLayer( "Ground" ) );
99
100         m_IsGrounded = hit.collider != null;
101         m_Animator.SetBool( "IsGrounded", m_IsGrounded );
102     }
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: PunStartup.cs Copy
80     public static void SetPunDemoBuildSettings()
81     {
82         // find path of pun guide
83         string[] tempPaths = Directory.GetDirectories(Application.dataPath + "/Photon Unity Networking", "Demos", SearchOption.AllDirectories);
84         if (tempPaths == null || tempPaths.Length != 1)
85         {
86             return;
87         }
88
89         // find scenes of guide
90         string guidePath = tempPaths[0];
91         tempPaths = Directory.GetFiles(guidePath, "*.unity", SearchOption.AllDirectories);
92
93         if (tempPaths == null || tempPaths.Length == 0)
94         {
95             return;
96         }
97
98         // add found guide scenes to build settings
99         List sceneAr = new List();
100         for (int i = 0; i < tempPaths.Length; i++)
101         {
102             //Debug.Log(tempPaths[i]);
103             string path = tempPaths[i].Substring(Application.dataPath.Length - "Assets".Length);
104             path = path.Replace('\\', '/');
105             //Debug.Log(path);
106
107             if (path.Contains("PUNGuide_M2H"))
108             {
109                 continue;
110             }
111
112             if (path.Contains("Hub"))
113             {
114                 sceneAr.Insert(0, new EditorBuildSettingsScene(path, true));
115                 continue;
116             }
117
118             sceneAr.Add(new EditorBuildSettingsScene(path, true));
119         }
120
121         EditorBuildSettings.scenes = sceneAr.ToArray();
122         EditorApplication.OpenScene(sceneAr[0].path);
123     }
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: 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: ClickDetector.cs Copy
7  void Update()
8     {
9         // if this player is not "it", the player can't tag anyone, so don't do anything on collision
10         if (PhotonNetwork.player.ID != GameLogic.playerWhoIsIt)
11         {
12             return;
13         }
14
15         if (Input.GetButton("Fire1"))
16         {
17             GameObject goPointedAt = RaycastObject(Input.mousePosition);
18
19             if (goPointedAt != null && goPointedAt != this.gameObject && goPointedAt.name.Equals("monsterprefab(Clone)", StringComparison.OrdinalIgnoreCase))
20             {
21                 PhotonView rootView = goPointedAt.transform.root.GetComponent();
22                 GameLogic.TagPlayer(rootView.owner.ID);
23             }
24         }
25  }
File name: ClickDetector.cs Copy
27     private GameObject RaycastObject(Vector2 screenPos)
28     {
29         RaycastHit info;
30         #if UNITY_3_5
31         Camera cam = Camera.mainCamera;
32         #else
33         Camera cam = Camera.main;
34         #endif
35
36         if (Physics.Raycast(cam.ScreenPointToRay(screenPos), out info, 200))
37         {
38             return info.collider.gameObject;
39         }
40
41         return null;
42     }
File name: PhotonConverter.cs Copy
323     static string PregReplace(string input, string[] pattern, string[] replacements)
324     {
325         if (replacements.Length != pattern.Length)
326             Debug.LogError("Replacement and Pattern Arrays must be balanced");
327
328         for (var i = 0; i < pattern.Length; i++)
329         {
330             input = Regex.Replace(input, pattern[i], replacements[i]);
331         }
332
333         return input;
334     }

Download file with original file name:Ray

Ray 118 lượt xem

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