TouchPhase









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

Featured Snippets


File name: InputToEvent.cs Copy
32     void Update()
33     {
34         if( DetectPointedAtGameObject )
35         {
36             goPointedAt = RaycastObject( Input.mousePosition );
37         }
38
39         if( Input.touchCount > 0 )
40         {
41             Touch touch = Input.GetTouch( 0 );
42             this.currentPos = touch.position;
43
44             if( touch.phase == TouchPhase.Began )
45             {
46                 Press( touch.position );
47             }
48             else if( touch.phase == TouchPhase.Ended )
49             {
50                 Release( touch.position );
51             }
52
53             return;
54         }
55
56         currentPos = Input.mousePosition;
57         if( Input.GetMouseButtonDown( 0 ) )
58         {
59             Press( Input.mousePosition );
60         }
61         if( Input.GetMouseButtonUp( 0 ) )
62         {
63             Release( Input.mousePosition );
64         }
65
66         if( Input.GetMouseButtonDown( 1 ) )
67         {
68             pressedPosition = Input.mousePosition;
69             lastGo = RaycastObject( pressedPosition );
70             if( lastGo != null )
71             {
72                 lastGo.SendMessage( "OnPressRight", SendMessageOptions.DontRequireReceiver );
73             }
74         }
75     }
File name: InstructionsScript.cs Copy
27  void OnGUI() {
28   if (this.gameScript.gameView == "instructions") {
29    GUI.skin = currentGUISkin;
30
31    this.gameScript.mainCamera.transform.eulerAngles = new Vector3 (120, 23, 0);
32
33    GUIStyle labelStyle = new GUIStyle(currentGUISkin.label);
34    labelStyle.alignment = TextAnchor.UpperLeft;
35    GUILayout.Label ("Instructions", "BigLabel");
36
37
38    scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(Screen.width), GUILayout.Height(Mathf.Ceil(Screen.height * .80f)));
39
40    GUILayout.Label ("Object", "Subheader");
41
42    GUILayout.Label (@"The object of 2048-3D is to"
43                  + " slide numbered blocks in such a way"
44                  + " so that blocks with the same numbers collide"
45                  + " and combine into a new block that is twice"
46                  + " as much as the originals until"
47                  + " the number 2048 is reached.", labelStyle);
48
49    GUILayout.Label ("Moving the Blocks", "Subheader");
50
51    GUILayout.Label (@"You cannot move blocks individually, but must"
52                 + " move all blocks simultaneously in the same direction."
53                 + " Blocks can move forward, backward, up, down, left"
54     + " and right along the green connectors."
55           + " Simply swipe any part of the screen to move up,"
56     + " down, left or right (keyboard: arrow keys). To move the"
57     + " blocks forward and backward use the"
58     + " big red arrow keys at the bottom of the screen (keyboard: a and z keys)."
59     + " When moving, all blocks that can slide in the chosen direction will move."
60     + " Any block moving toward another block with the same number will collide "
61        + " and form a single block with twice the number as the originals", labelStyle);
62
63
64    GUILayout.Label ("New Blocks", "Subheader");
65
66    GUILayout.Label (@"After each move is"
67                 + " made a new block will appear randomly in an empty position."
68                 + " This block will have a number of either 2 or 4."
69        + " For an extra challenge, there is a game option you can"
70        + " set so that zeros can also be assinged to a new block."
71        + " Zeros act like any other number in that they can"
72        + " collide with other zeros to make a block twice as much "
73        + " (which is still zero).", labelStyle);
74
75
76
77    GUILayout.Label ("Scoring and Finishing", "Subheader");
78
79    GUILayout.Label(@"For every block collision that occurs you receive"
80                 + " the number of points of the newly"
81                 + " created block. If after making a move"
82                 + " all positions are filled and no new"
83                 + " moves are possible, the game ends."
84        + " A separate high score / highest block is kept for each"
85        + " distinct combination of game options", labelStyle);
86
87
88    GUILayout.Label ("Game Layout Options", "Subheader");
89
90    GUILayout.Label (@"When I first made this game there"
91            + " was only one game layout, a 3x3x3 cube."
92            + " After testing it a bit, it was way to easy"
93            + " so the zero option was added."
94            + " It was still way to easy "
95            + " (e.g. you could swipe without even looking and get pretty far)."
96            + " Therefore there are now several diffent game layouts that"
97            + " make the game more challenging and fun.", labelStyle);
98
99    GUILayout.Label ("Game Timer Option", "Subheader");
100
101    GUILayout.Label (@"To give yourself even more of a challenge"
102                     + " you can set game options to include a timer."
103                     + " If a timer is chosen you have a specific"
104                     + " amount of time to combined blocks to make the 64 block."
105                     + " If you run out of time the game is over."
106                     + " If you reach your target before the timer runs down you will"
107                     + " receive additional time to reach the next target."
108                     + " The time you received is as follows: \n"
109                     + " 64: option time + 5 seconds (because the first one is the hardest!)\n"
110                     + " 128: option time\n"
111                     + " 256: 2X option time\n"
112                     + " 512: 4X option time \n"
113                     + " 1024: 8X option time \n"
114                     + " you get the idea.", labelStyle);
115
116
117    GUILayout.Label ("Acknowledgements \nand Confessions", "Subheader");
118
119    GUILayout.Label (@"2048-3D is based upon the original" +
120                     " 2048 game designed by Gabriele Cirulli " +
121                     " \n\n" +
122                     " Sound effects by freeSFX http://www.freesfx.co.uk.\n\n" +
123                     " This game was designed using the Unity3D game engine.\n\n" +
124                     " FOR MORE PROJECTS VISIT:" +
125                     " https://code-projects.org/", labelStyle);
126
127
128    foreach (Touch touch in Input.touches) {
129     if (touch.phase == TouchPhase.Moved)
130     {
131      // dragging
132      this.scrollPosition.y += touch.deltaPosition.y;
133     }
134    }
135    GUILayout.EndScrollView();
136
137    if (GUILayout.Button ("Return to Menu")) {
138     this.gameScript.gameView = "menu";
139    }
140   }
141  }
File name: OptionsScript.cs Copy
168  void OnGUI() {
169   if (this.gameScript.gameView == "options") {
170    this.gameScript.mainCamera.transform.eulerAngles = new Vector3 (120, 23, 0);
171
172    GUI.skin = this.gameScript.currentGUISkin;
173
174    //check to see if any options changed
175    if (previous_use_0 != use_0) {
176     this.setOption ("use_0", this.use_0);
177     GameControllerScript.performRestart = true;
178    }
179
180    if (this.previous_board_type != this.board_type) {
181     this.setOption ("board_type", this.board_type);
182     GameControllerScript.performRestart = true;
183    }
184
185    if (previous_play_sounds != play_sounds) {
186     this.setOption ("play_sounds", this.play_sounds);
187    }
188
189    if (this.previous_timer_duration != this.timer_duration) {
190     this.setOption ("timer_duration", this.timer_duration);
191     GameControllerScript.performRestart = true;
192    }
193
194
195
196    //set the label
197    GUILayout.Label ("Options", "BigLabel");
198
199    scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(Screen.width), GUILayout.Height(Mathf.Ceil(Screen.height * .80f)));
200
201
202
203    //Sounds
204    GUILayout.BeginHorizontal ();
205    if (GUILayout.Toggle (this.play_sounds, "Play Sounds", currentGUISkin.toggle)) {
206     this.play_sounds = true;
207    }
208    else {
209     this.play_sounds = false;
210    }
211    GUILayout.Label ( "Play Sounds", "ToggleLabel");
212    GUILayout.EndHorizontal();
213
214
215    GUILayout.Label ("WARNING! Changing any of the following options will cause the game to reset!", "ToggleLabelWarning");
216
217    GUILayout.Label ("Game Board Type", "Subheader");
218    //Game Board Type
219    GUILayout.BeginHorizontal ();
220    if (GUILayout.Toggle (this.board_type == "Solid Cube", "Solid Cube", currentGUISkin.toggle)) {
221     this.board_type = "Solid Cube";
222    }
223    GUILayout.Label ( "Solid Cube (27 Blocks)", "ToggleLabel");
224    GUILayout.EndHorizontal();
225
226
227    GUILayout.BeginHorizontal ();
228    if (GUILayout.Toggle (this.board_type == "Hollow Cube", "Hollow Cube", currentGUISkin.toggle)) {
229     this.board_type = "Hollow Cube";
230    }
231    GUILayout.Label ( "Hollow Cube (26 Blocks)", "ToggleLabel");
232    GUILayout.EndHorizontal();
233
234
235    GUILayout.BeginHorizontal ();
236    if (GUILayout.Toggle (this.board_type == "Four Walls", "Four Walls", currentGUISkin.toggle)) {
237     this.board_type = "Four Walls";
238    }
239    GUILayout.Label ( "Four Walls (24 Blocks)", "ToggleLabel");
240    GUILayout.EndHorizontal();
241
242
243    GUILayout.BeginHorizontal ();
244    if (GUILayout.Toggle (this.board_type == "Box Outline", "Box Outline", currentGUISkin.toggle)) {
245     this.board_type = "Box Outline";
246    }
247    GUILayout.Label ( "Cube Outline (20 Blocks)", "ToggleLabel");
248    GUILayout.EndHorizontal();
249
250
251
252    GUILayout.BeginHorizontal ();
253    if (GUILayout.Toggle (this.board_type == "No Corners", "No Corners", currentGUISkin.toggle)) {
254     this.board_type = "No Corners";
255    }
256    GUILayout.Label ( "No Corners (19 Blocks)", "ToggleLabel");
257    GUILayout.EndHorizontal();
258
259
260    GUILayout.BeginHorizontal ();
261    if (GUILayout.Toggle (this.board_type == "No Corners/Center", "No Corners/Center", currentGUISkin.toggle)) {
262     this.board_type = "No Corners/Center";
263    }
264    GUILayout.Label ( "No Corners/Center (18 Blocks)", "ToggleLabel");
265    GUILayout.EndHorizontal();
266
267
268    //TIMER OPTIONS ####################################################
269    GUILayout.Label ("Timer", "Subheader");
270
271    foreach (int i in this.GetTimerDurationTimes())
272    {
273     GUILayout.BeginHorizontal ();
274     if (GUILayout.Toggle (this.timer_duration == i, "", currentGUISkin.toggle)) {
275      this.timer_duration = i;
276     }
277     GUILayout.Label (TimerDurationToString (i), "ToggleLabel");
278     GUILayout.EndHorizontal();
279    }
280
281
282
283
284    //Other OPTIONS ####################################################
285    GUILayout.Label ("Block Numbers", "Subheader");
286
287    //Use Zeros
288    GUILayout.BeginHorizontal ();
289    if (GUILayout.Toggle (use_0, "Use 0s (Note: Changing this will reset the current game!)", currentGUISkin.toggle)) {
290     use_0 = true;
291    }
292    else {
293     use_0 = false;
294    }
295    GUILayout.Label ( "Use Zeros", "ToggleLabel");
296    GUILayout.EndHorizontal();
297
298
299
300    foreach (Touch touch in Input.touches) {
301     if (touch.phase == TouchPhase.Moved)
302     {
303      // dragging
304      scrollPosition.y += touch.deltaPosition.y;
305     }
306    }
307
308    GUILayout.EndScrollView();
309
310    if (GUILayout.Button ("Return to Menu", "Button")) {
311     gameScript.gameView = "menu";
312    }
313   }
314  }
File name: SwipeListenerScript.cs Copy
10  void Update () {
11   //transform.guiText.text = "my text";
12   int fingerCount = 0;
13   foreach (Touch touch in Input.touches) {
14    if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
15     fingerCount++;
16
17    if (touch.phase == TouchPhase.Began)
18    {
19     startPosition = touch.position;
20     lastPosition = touch.position;
21    }
22
23    if (touch.phase == TouchPhase.Moved )
24    {
25     lastPosition = touch.position;
26    }
27    if(touch.phase == TouchPhase.Ended)
28    {
29
30     if((startPosition.x - lastPosition.x) > 80) // left swipe
31     {
32      this.Swipe ("x", -1);
33     }
34     else if((startPosition.x - lastPosition.x) < -80) // right swipe
35     {
36      this.Swipe ("x", 1);
37     }
38     else if((startPosition.y - lastPosition.y) < -80 ) // up swipe
39     {
40      this.Swipe ("y", 1);
41     }
42     else if((startPosition.y - lastPosition.y) > 80 ) // down swipe
43     {
44      this.Swipe ("y", -1);
45     }
46
47    }
48   }
49  }
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  }
File name: CameraFollow.cs Copy
91  void TouchMoveCamera(){
92   if(allowToMove){
93
94    /*if(Input.touchCount > 0){
95     Touch touch = Input.GetTouch (0);
96
97     Transform cam = gameObject.transform;
98
99
100     if(touch.phase == TouchPhase.Began){
101      cam = touch.position;
102     }else if(touch.phase == TouchPhase.Moved){
103
104     }
105    }*/
106
107    if(Input.touchCount > 0){
108     Touch touch = Input.GetTouch (0);
109
110     Transform cam = gameObject.transform;
111     if (touch.position.x > 300) {
112      if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Stationary){
113       camPos = touch.position;
114      }else if(touch.phase == TouchPhase.Moved){
115       cam.position = cam.position + (new Vector3 ((camPos.x - touch.position.x), 0, 0) * dragSpeed * Time.deltaTime);
116       float camX = cam.position.x;
117       camX = Mathf.Clamp (camX, leftBound.transform.position.x, rightBound.transform.position.x);
118       cam.position = new Vector3 (camX, cam.position.y, cam.position.z);
119      }
120     }
121
122    }
123
124   }
125  }
File name: Cannon.cs Copy
63  void TouchCannonShoot(){
64   if(Input.touchCount > 0){
65    Touch touch = Input.GetTouch (0);
66
67    touchPos = Camera.main.ScreenToWorldPoint (touch.position);
68
69    Vector2 touchRayHit = new Vector2 (touchPos.x, touchPos.y);
70
71    RaycastHit2D hit = Physics2D.Raycast (touchRayHit , Vector2.zero);
72
73    if(hit.collider != null){
74     if(hit.collider.CompareTag("Player")){
75      if(touch.phase == TouchPhase.Stationary){
76       if (shot != 0) {
77        UpdatePowerLevel ();
78        isCharging = true;
79       }
80      }else if(touch.phase == TouchPhase.Ended){
81       if (shot != 0) {
82        GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
83        newCannonBullet.transform.GetComponent ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
84        if (GameController.instance != null && MusicController.instance != null) {
85         if (GameController.instance.isMusicOn) {
86          audioSource.PlayOneShot (cannonShot);
87         }
88        }
89        shot--;
90        powerLevel.value = 0;
91        readyToShoot = false;
92        isCharging = false;
93       }
94      }
95     }
96    }
97
98    /*if(touch.phase == TouchPhase.Stationary){
99     if (shot != 0) {
100      UpdatePowerLevel ();
101     }
102    }else if(touch.phase == TouchPhase.Ended){
103     if (shot != 0) {
104      GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
105      newCannonBullet.transform.GetComponent ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
106      if (GameController.instance != null && MusicController.instance != null) {
107       if (GameController.instance.isMusicOn) {
108        audioSource.PlayOneShot (cannonShot);
109       }
110      }
111      shot--;
112      powerLevel.value = 0;
113      readyToShoot = false;
114     }
115    }*/
116
117   }
118  }
File name: Cannon.cs Copy
172  void TouchCannonMovement(){
173   if(Input.touchCount > 0){
174    Touch touch = Input.GetTouch (0);
175
176    if (touch.position.x < 300 && !isCharging && touch.position.y > 160) {
177
178     if (touch.phase == TouchPhase.Moved) {
179      Vector2 touchDeltaPosition = touch.deltaPosition;
180      direction = touchDeltaPosition.normalized;
181
182      if (direction.y > 0 && touchDeltaPosition.x > -10 && touchDeltaPosition.x < 10) {
183       currentRotation.z += 50f * Time.deltaTime;
184      } else if (direction.y < 0 && touchDeltaPosition.x > -10 && touchDeltaPosition.x < 10) {
185       currentRotation.z -= 50f * Time.deltaTime;
186      }
187
188     }
189    }
190   }
191
192   currentRotation.z = Mathf.Clamp(currentRotation.z, minRot, maxRot);
193
194   transform.rotation = Quaternion.Euler (currentRotation);
195
196  }
File name: Player.cs Copy
56   private void Update ()
57   {
58    //If it's not the player's turn, exit the function.
59    if(!GameManager.instance.playersTurn) return;
60
61    int horizontal = 0; //Used to store the horizontal move direction.
62    int vertical = 0; //Used to store the vertical move direction.
63
64    //Check if we are running either in the Unity editor or in a standalone build.
65#if UNITY_STANDALONE || UNITY_WEBPLAYER
66
67    //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
68    horizontal = (int) (Input.GetAxisRaw ("Horizontal"));
69
70    //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
71    vertical = (int) (Input.GetAxisRaw ("Vertical"));
72
73    //Check if moving horizontally, if so set vertical to zero.
74    if(horizontal != 0)
75    {
76     vertical = 0;
77    }
78    //Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
79#elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
80
81    //Check if Input has registered more than zero touches
82    if (Input.touchCount > 0)
83    {
84     //Store the first touch detected.
85     Touch myTouch = Input.touches[0];
86
87     //Check if the phase of that touch equals Began
88     if (myTouch.phase == TouchPhase.Began)
89     {
90      //If so, set touchOrigin to the position of that touch
91      touchOrigin = myTouch.position;
92     }
93
94     //If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
95     else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
96     {
97      //Set touchEnd to equal the position of this touch
98      Vector2 touchEnd = myTouch.position;
99
100      //Calculate the difference between the beginning and end of the touch on the x axis.
101      float x = touchEnd.x - touchOrigin.x;
102
103      //Calculate the difference between the beginning and end of the touch on the y axis.
104      float y = touchEnd.y - touchOrigin.y;
105
106      //Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
107      touchOrigin.x = -1;
108
109      //Check if the difference along the x axis is greater than the difference along the y axis.
110      if (Mathf.Abs(x) > Mathf.Abs(y))
111       //If x is greater than zero, set horizontal to 1, otherwise set it to -1
112       horizontal = x > 0 ? 1 : -1;
113      else
114       //If y is greater than zero, set horizontal to 1, otherwise set it to -1
115       vertical = y > 0 ? 1 : -1;
116     }
117    }
118
119#endif //End of mobile platform dependendent compilation section started above with #elif
120    //Check if we have a non-zero value for horizontal or vertical
121    if(horizontal != 0 || vertical != 0)
122    {
123     //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
124     //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
125     AttemptMove (horizontal, vertical);
126    }
127   }

TouchPhase 170 lượt xem

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