Search Unity

Screen click position?

Discussion in 'Scripting' started by shawnrevels, Aug 1, 2015.

  1. shawnrevels

    shawnrevels

    Joined:
    Aug 13, 2014
    Posts:
    86
    So i have a cool game going on. I have a script that controls the game itself. I don't know where i went wrong but where ever i click on the screen my game objects move. If i click the menu button, they move. I attached a background image in the area that i wanted to be swipe-able and it didn't seem to work. The object is to swipe bubbles that are the same color into another of the same color to collect points. But the swipe seems to be set to the whole screen. IE world position. Any help is welcome. Thanks. This is my game script.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. // this script is the main script and contains
    6. // - game logic
    7. // - input methods
    8. // - artificial intelligence
    9.  
    10. public class Game : MonoBehaviour {
    11.  
    12.     // native resolution of this game is 1024x768
    13.     private float nativeWidth = 1024;
    14.     private float nativeHeight = 768;
    15.  
    16.     // references to GUI objects
    17.  
    18.     public Texture2D buttonTexture;
    19.     public Texture2D backgroundTexture;
    20.  
    21.     public GameObject backGround;
    22.     // reference to the game tile
    23.     public GameObject slider;
    24.     // reference to the cell the game tile is in
    25.     public GameObject cell;
    26.     string scoreText;
    27.     public GameObject restartButton;
    28.     string scoreMessage;
    29.    
    30.     // organize the cells in an array
    31.     GameObject[] cells;
    32.    
    33.     // size of game grid
    34.     // game grid is 4x4
    35.     public int SIZE = 4;
    36.     int[,] grid;
    37.  
    38.     // to save the score, best score and the actual move
    39.     int score = 0 ;
    40.     int best = 0;
    41.     int move ;
    42.     public Rect labelPosition;
    43.     string labelText;
    44.     public GUIStyle labelStyle;
    45.     public Rect labelPosition1;
    46.     public Rect labelPosition3;
    47.     string labelText1;
    48.     public GUIStyle labelStyle1;
    49.     public GUIStyle labelStyle3;
    50.    
    51.     // if a new tile is generated, which value(s) can it be?
    52.     int lowestNewTileValue = 2;
    53.     int highestNewTileValue = 4;
    54.  
    55.     float horizontalSpacing = -2.2f;
    56.     float verticalSpacing = 2.2f;
    57.     float tileSize = 1.28f;
    58.     float spacing = 0.2f;
    59.  
    60.     GameObject slider1;
    61.  
    62.     // Game state management is done via a finite state machine (fsm)
    63.     // this is the data structure to determine which state the game is currently in
    64.     enum GameStates {
    65.         loaded,
    66.         waitingForInput,
    67.         checkAnimation,
    68.         check,
    69.         over,
    70.     };
    71.  
    72.     GameStates gameState;
    73.  
    74.     // which direction are we moving to
    75.     enum Movement {
    76.         none,
    77.         left,
    78.         right,
    79.         up,
    80.         down,
    81.     };
    82.  
    83.     Movement movement;
    84.  
    85.     // input viy xBox controller is possible
    86.     struct DPad {
    87.         public float leftRight;
    88.         public float upDown;
    89.     };
    90.  
    91.     DPad oldDPad;
    92.  
    93.     bool success;
    94.     bool animationFinished;
    95.  
    96.     // Variables for swipe gestures
    97.     Vector2 firstPressPos;
    98.     Vector2 secondPressPos;
    99.     Vector2 currentSwipe;
    100.  
    101.     bool solver;
    102.     bool solver1;
    103.     float elapsed;
    104.     float solverInterval = 0.2f;
    105.     float sliderDepth;
    106.  
    107.     // we do not calculate every possible move -
    108.     // since the board is symmetric, it can be rotated by 90 degree
    109.     // so only direction must be calculated
    110.     Vector2[,,] rotMatrix;
    111.  
    112.  
    113.     //
    114.     // void Start()
    115.     //
    116.     // this method initializes the game
    117.     //
    118.     void Start () {
    119.         // count the moves
    120.         move = 0;
    121.  
    122.         // in which direction are we moving
    123.         // we are not moving at all
    124.         movement = Movement.none;
    125.  
    126.         // initialize the game grid
    127.         grid = new int[SIZE, SIZE];
    128.  
    129.         // initialize the background
    130.         backGround = (GameObject)Instantiate(backGround, new Vector3(0,0,0), Quaternion.identity);
    131.         // set the score
    132.         score = 0;
    133.         // hiscore will be stored via Playerprefs
    134.         // this is a very comfortable way to store information
    135.         // (this even works in the web player)
    136.         best = PlayerPrefs.GetInt("hiscore",0);
    137.         // generate the cells' array
    138.         cells = new GameObject[16];
    139.  
    140.         int i = 0;
    141.         for (int y = 0; y < SIZE; y++) {
    142.             for (int x = 0; x < SIZE; x++) {
    143.                 // initialize the game grid
    144.                 grid [x,y] = 0;
    145.                 cells[i] = (GameObject)Instantiate (cell, new Vector3(horizontalSpacing+(tileSize+spacing)*x,verticalSpacing-(tileSize+spacing)*y,-0.1f), Quaternion.identity);
    146.                 cells[i].name += x + "_" + y ;
    147.                 i++;
    148.             }
    149.         }
    150.  
    151.         // set the AI to false
    152.         solver = false;
    153.         solver1 = false;
    154.         sliderDepth = 1;
    155.  
    156.         // now initialize the matrix
    157.         // for rotating the game board
    158.         rotMatrix = new Vector2[4,4,4];
    159.  
    160.         for (int y = 0; y < SIZE; y++) {
    161.             for (int x = 0; x < SIZE; x++) {
    162.                 rotMatrix[0,x,y] = new Vector2(x,y);
    163.                 rotMatrix[1,x,y] = new Vector2(x,y);
    164.                 rotMatrix[2,x,y] = new Vector2(x,y);
    165.                 rotMatrix[3,x,y] = new Vector2(x,y);
    166.             }
    167.         }
    168.  
    169.         rotateMatrix(rotMatrix,1);
    170.         rotateMatrix(rotMatrix,2);
    171.         rotateMatrix(rotMatrix,2);
    172.         rotateMatrix(rotMatrix,3);
    173.         rotateMatrix(rotMatrix,3);
    174.         rotateMatrix(rotMatrix,3);
    175.  
    176.         // set the actual gameState
    177.         gameState = GameStates.loaded;
    178.     }
    179.    
    180.     //
    181.     // void rotateMatrix(Vector2[,,] grid, int index)
    182.     //
    183.     // do the rotation
    184.     //
    185.     // remember: a move to the right is equally to
    186.     // rotating the grid 90° counterclockwise and
    187.     // perform a move upwards
    188.     //
    189.     public void rotateMatrix(Vector2[,,] grid, int index) {
    190.         for (int y = 0; y < SIZE/2; y++) {
    191.             for (int x = y; x < SIZE - y - 1; x++) {
    192.                 Vector2 tmp = grid[index,y,x];
    193.                 grid[index,y,x] = grid[index,x,SIZE-y-1];
    194.                 grid[index,x,SIZE-y-1] = grid[index,SIZE-y-1,SIZE-x-1];
    195.                 grid[index,SIZE-y-1,SIZE-x-1]=grid[index,SIZE-x-1,y];
    196.                 grid[index,SIZE-x-1,y]=tmp;
    197.             }
    198.         }
    199.     }
    200.  
    201.    
    202.  
    203.     //
    204.     // void Update()
    205.     //
    206.     // this is the main game loop
    207.     //
    208.     void Update () {
    209.        
    210.         labelText = "" + score.ToString();
    211.         labelText1 = "" + best.ToString();
    212.         // check which state we are in
    213.         switch (gameState) {
    214.             // the game is started
    215.             // reset the game grid
    216.             // generate two random staring tiles
    217.             // change state and for the player to make some input
    218.         case GameStates.loaded:
    219.             resetGrid();
    220.             generateRandomTile();
    221.             generateRandomTile();
    222.             gameState = GameStates.waitingForInput;
    223.             break;
    224.  
    225.             // if the player can make a move, we have two possibilites
    226.             // 1) AI plays
    227.             // 2) player makes a move
    228.         case GameStates.waitingForInput:
    229.             // AI makes move
    230.             if (solver) {
    231.                 elapsed += Time.deltaTime;
    232.                 if (elapsed > solverInterval) {
    233.                     elapsed -= solverInterval;
    234.                     KI(grid);
    235.                 }
    236.             }
    237.             // player makes move
    238.             else {
    239.                 checkInput ();
    240.             }
    241.             // so we made a move
    242.             // check which move we made
    243.             switch (movement) {
    244.                 // we did move all tiles to the left
    245.             case Movement.left:
    246.                 success = moveLeft();
    247.                 animateTiles();
    248.                 gameState = GameStates.checkAnimation;
    249.                 break;
    250.                 // we did move all tiles to the right
    251.             case Movement.right:
    252.                 success = moveRight();
    253.                 animateTiles ();
    254.                 gameState = GameStates.checkAnimation;
    255.                 break;
    256.                 // we did move all tiles up
    257.             case Movement.up:
    258.                 success = moveUp(0);
    259.                 animateTiles();
    260.                 gameState = GameStates.checkAnimation;
    261.                 break;
    262.                 // we did move all tiles down
    263.             case Movement.down:
    264.                 success = moveDown();
    265.                 animateTiles();
    266.                 gameState = GameStates.checkAnimation;
    267.                 break;
    268.                 }
    269.             break;
    270.  
    271.             // movement is joined to animation
    272.             // animation must not be disturbed, so wait until animation is done
    273.         case GameStates.checkAnimation:
    274.             if (checkForAnimation())
    275.                 gameState = GameStates.check;
    276.             break;
    277.  
    278.             // ok, the move is over
    279.             // show the game grid and
    280.             // generate a new random tile
    281.         case GameStates.check:
    282.             if (success) {
    283.                 showTheGrid();
    284.                 generateRandomTile();
    285.                 success = false;
    286.             }
    287.             movement = Movement.none;
    288.  
    289.             // check if board is completely filled
    290.             // and no further move is possible
    291.             if (gameEnded()) {
    292.                 // if so, the gane is over
    293.                 gameState = GameStates.over;
    294.             }
    295.             else {
    296.                 // else the player can make a new move
    297.                 gameState = GameStates.waitingForInput;
    298.             }
    299.             break;
    300.  
    301.             // the game is over
    302.         case GameStates.over:
    303.             // is the new score better than the previously saved one
    304.             if (score > best) {
    305.                 // then save the better score to PlayerPrefs
    306.                 PlayerPrefs.SetInt("hiscore",score);
    307.                 best = score;
    308.             }
    309.             break;
    310.         }
    311.     }
    312.     public void saveScore()
    313.     {
    314.         // is the new score better than the previously saved one
    315.             if (score > best) {
    316.                 // then save the better score to PlayerPrefs
    317.                 PlayerPrefs.SetInt("hiscore",score);
    318.                 best = score;
    319.                 resetGrid();
    320.                 gameState = GameStates.loaded;
    321.             }
    322.            
    323.    
    324.     }
    325.  
    326.  
    327.     //
    328.     // void animateTiles()
    329.     //
    330.     // this method gets all tiles on the grid
    331.     // (this is simple, since they're tagged "tile")
    332.     // animate all the tiles
    333.     //
    334.  
    335.     public void animateTiles() {
    336.         animationFinished = false;
    337.         GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
    338.         foreach (GameObject tile in tiles) {
    339.             tile.GetComponent<TileAnimator>().animatePositionChange();
    340.         }
    341.     }
    342.  
    343.  
    344.     //
    345.     // void chekForAnimation()
    346.     //
    347.     // this method checks if there is currently
    348.     // an animation and returns true or false
    349.     //
    350.     // remember: only one animation at the time
    351.  
    352.     public bool checkForAnimation() {
    353.         bool animationFinished = true;
    354.         GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
    355.         foreach (GameObject tile in tiles) {
    356.             animationFinished = animationFinished && tile.GetComponent<TileAnimator>().isFinished();
    357.         }
    358.         return animationFinished;
    359.     }
    360.  
    361.  
    362.     //
    363.     // void checkInput()
    364.     //
    365.     // this game allows a lot of different input methods
    366.     // Keyboard            : arrow keys
    367.     // xBox-Controller    : Buttons and dPad
    368.     // Touch            : swipe gestures (also works with mouse)
    369.     //
    370.  
    371.     public void checkInput() {
    372.         checkKeyboardInput();
    373.         checkXBoxButtons();
    374.         checkXBoxDPad();
    375.         checkXBoxStartButton();
    376.         checkSwipeTouch();
    377.         checkSwipeClick();
    378.     }
    379.  
    380.  
    381.     //
    382.     // void checkKeyboardInput()
    383.     //
    384.     // check the arrow keys and set the movement enum
    385.     //
    386.  
    387.     void checkKeyboardInput() {
    388.         if  (Input.GetKeyUp(KeyCode.UpArrow))
    389.             movement = Movement.up;
    390.         if  (Input.GetKeyUp(KeyCode.DownArrow))
    391.             movement = Movement.down;
    392.         if  (Input.GetKeyUp(KeyCode.LeftArrow))
    393.             movement = Movement.left;
    394.         if  (Input.GetKeyUp(KeyCode.RightArrow))
    395.             movement = Movement.right;
    396.     }
    397.  
    398.  
    399.     //
    400.     // void checkXBoxButtons()
    401.     //
    402.     // check the A, B, X, Y Button on xBox-Controller
    403.     // and set the movement enum
    404.     //
    405.  
    406.     void checkXBoxButtons() {
    407.         if (Input.GetButtonUp("XBox_Y_Button"))
    408.             movement = Movement.up;
    409.         if (Input.GetButtonUp("XBox_A_Button"))
    410.             movement = Movement.down;
    411.         if (Input.GetButtonUp("XBox_B_Button"))
    412.             movement= Movement.right;
    413.         if (Input.GetButtonUp("XBox_X_Button"))
    414.             movement = Movement.left;
    415.     }
    416.  
    417.  
    418.     //
    419.     // void checkXBoxDPad()
    420.     //
    421.     // check the dPad on the xBox-Controller
    422.     // and set the movement enum
    423.     //
    424.  
    425.     void checkXBoxDPad() {
    426.         DPad newDPad;
    427.         newDPad.leftRight = Input.GetAxis("XBox_DPad_Horizontal");
    428.         newDPad.upDown = Input.GetAxis("XBox_DPad_Vertical");
    429.         if (!newDPad.Equals(oldDPad)) {
    430.             if (newDPad.leftRight <  -0.1f)
    431.                 movement = Movement.left;
    432.             if (newDPad.leftRight > 0.1f)
    433.                 movement = Movement.right;
    434.             if (newDPad.upDown >  0.1f)
    435.                 movement = Movement.up;
    436.             if (newDPad.upDown < -0.1f)
    437.                 movement = Movement.down;
    438.         }
    439.         oldDPad = newDPad;
    440.     }
    441.  
    442.  
    443.     //
    444.     // void checkXBoxStartButton()
    445.     //
    446.     // reset the game when player presses the start button
    447.     //
    448.  
    449.     public void checkXBoxStartButton() {
    450.         if (Input.GetButtonUp("XBox_Start_Button")) {
    451.             resetGrid();
    452.             gameState = GameStates.loaded;
    453.         }
    454.     }
    455.  
    456.  
    457.     //
    458.     // void checkSwipeTouch()
    459.     //
    460.     // now for the last input method
    461.     // (and the most important nowadays)
    462.     // Check for Touch input and swipe gestures
    463.     //
    464.  
    465.     void checkSwipeTouch() {
    466.        
    467.         if (Input.touches.Length > 0)
    468.         {
    469.             Touch t = Input.GetTouch(0);
    470.             if(t.phase == TouchPhase.Began) {
    471.                
    472.                 //save began touch 2d point
    473.                 firstPressPos = new Vector2(t.position.x,t.position.y);
    474.             }
    475.  
    476.             if (t.phase == TouchPhase.Ended) {
    477.                 //save ended touch 2d point
    478.                 secondPressPos = new Vector2(t.position.x,t.position.y);
    479.                
    480.                 //create vector from the two points
    481.                 currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    482.                
    483.                 //normalize the 2d vector
    484.                 currentSwipe.Normalize();
    485.                
    486.                 //swipe upwards
    487.                 if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    488.                     movement = Movement.up;
    489.                 }
    490.  
    491.                 //swipe down
    492.                 if(currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    493.                     movement = Movement.down;
    494.                 }
    495.  
    496.                 //swipe left
    497.                 if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    498.                     movement = Movement.left;
    499.                 }
    500.  
    501.                 //swipe right
    502.                 if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f){
    503.                     movement = Movement.right;
    504.                 }
    505.             }
    506.         }
    507.     }
    508.  
    509.     void checkSwipeClick() {
    510.         if(Input.GetMouseButtonDown(0))
    511.         {
    512.             //save began touch 2d point
    513.             firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    514.         }
    515.  
    516.         if(Input.GetMouseButtonUp(0))
    517.         {
    518.             //save ended touch 2d point
    519.             secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    520.            
    521.             //create vector from the two points
    522.             currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    523.            
    524.             //normalize the 2d vector
    525.             currentSwipe.Normalize();
    526.            
    527.             //swipe upwards
    528.             if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
    529.             {
    530.                 movement = Movement.up;
    531.             }
    532.             //swipe down
    533.             if(currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
    534.             {
    535.                 movement = Movement.down;
    536.             }
    537.             //swipe left
    538.             if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
    539.             {
    540.                 movement = Movement.left;
    541.             }
    542.             //swipe right
    543.             if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
    544.             {
    545.                 movement = Movement.right;
    546.             }
    547.         }
    548.     }
    549.  
    550.  
    551.     //
    552.     // Vector2 worldToGridPosition
    553.     //
    554.     // this method converts input-positions on the screen to game-grid positions
    555.     //
    556.  
    557.     public Vector2 worldToGridPosition(Vector3 position) {
    558.         Vector2 gridPosition = new Vector2();
    559.         gridPosition.x = (position.x - horizontalSpacing)/(tileSize+spacing);
    560.         gridPosition.y = -(position.y - verticalSpacing)/(tileSize+spacing);
    561.         return gridPosition;
    562.     }
    563.  
    564.  
    565.     //
    566.     // Vector3 gridToWorldPosition
    567.     //
    568.     // convert grid Position to position on the screen
    569.     // --> world position
    570.     //
    571.  
    572.     public Vector3 gridToWorldPosition(int x, int y){
    573.         return new Vector3(horizontalSpacing+(tileSize+spacing)*x,verticalSpacing-(tileSize+spacing)*y,-0.2f);
    574.     }
    575.  
    576.  
    577.     //
    578.     // GameObject getObjectAtGridPosition
    579.     //
    580.     // use a Raycast to check the actual grid position
    581.     // for a gameObject
    582.     //
    583.  
    584.     public GameObject getObjectAtGridPosition(int x, int y) {
    585.         RaycastHit hit;
    586.         // get the current world position
    587.         Vector3 gridPosition = gridToWorldPosition(x,y);
    588.         // step back from the object, so we can shoot a ray
    589.         // (otherwise, it will hit the cell container or the background)
    590.         gridPosition.z -= 0.2f;
    591.         // cast a ray and see if we hit something
    592.         if (Physics.Raycast(gridPosition, new Vector3(0,0,1),out hit))
    593.         {
    594.             // is the GameObject found a tile?
    595.             Tile tile = hit.collider.GetComponent<Tile>();
    596.             // then return the gameObject found at position (x,y)
    597.             if (tile != null)
    598.                 return hit.collider.gameObject;
    599.         }
    600.         // sorry, we did not find an gameObject
    601.         return null;
    602.     }
    603.  
    604.  
    605.     //
    606.     // int getCurrentTiles
    607.     //
    608.     // get the number of tiles on the grid
    609.     // this method is used to check the win/lose condition
    610.     // if the grid is ull and no move can be done, the game is over
    611.     //
    612.  
    613.     public int getCurrentTiles(){
    614.         // reset counter to zero
    615.         int tileAmount = 0;
    616.         // iterate the grid
    617.         for (int y = 0; y < SIZE; y++) {
    618.             for (int x = 0; x < SIZE; x++) {
    619.                 // if grid is not zero,
    620.                 // increment the counter
    621.                 if (grid[x,y] != 0) {
    622.                     tileAmount++;
    623.                 }
    624.             }
    625.         }
    626.         // return the calculated number of cells
    627.         return tileAmount;
    628.     }
    629.    
    630.  
    631.     //
    632.     // void showTheGrid
    633.     //
    634.     // this method refreshes the grid
    635.     // it destroy relics of the last game iteration and produces fresh tiles
    636.     //
    637.  
    638.     public void showTheGrid() {
    639.         // eliminate the game Objects on the grid (view)
    640.         GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
    641.         foreach (GameObject tile in tiles) {
    642.             Destroy(tile);
    643.         }
    644.         for (int y = 0; y < SIZE; y++) {
    645.             for (int x = 0; x < SIZE; x++) {
    646.                 if (grid[x,y] != 0){
    647.                     slider1 = (GameObject)Instantiate (slider, gridToWorldPosition(x,y), Quaternion.Euler (new Vector3(0,0,180)));
    648.                     slider1.name = x + "_" + y;
    649.                     slider1.GetComponent<Tile>().setValue(grid[x,y]);
    650.                 }
    651.             }
    652.         }
    653.     }
    654.  
    655.  
    656.     //
    657.     // void generateRandomTile
    658.     //
    659.     // create a random tile on the grid
    660.     // this is done every move
    661.     //
    662.  
    663.     public void generateRandomTile(){
    664.         // can we create tiles anymore?
    665.         if (getCurrentTiles() < SIZE*SIZE) {
    666.             int value;
    667.             // yes, we can... so generate a random number...
    668.             float twoOrFour = Random.Range(0,0.99f);
    669.             // ... and choose a 2 or 4, respectively
    670.             if (twoOrFour >= 0.9f) {
    671.                 value = highestNewTileValue;
    672.             }
    673.             else {
    674.                 value = lowestNewTileValue;
    675.             }
    676.  
    677.             // generate a list of cells
    678.             List<Vector2> availableCells = new List<Vector2>();
    679.             // now find all empty places on te grid
    680.             for (int y = 0; y < SIZE; y++) {
    681.                 for (int x = 0; x < SIZE; x++) {
    682.                     if (grid[x,y] == 0) {
    683.                         Vector2 available = new Vector2(x,y);
    684.                         // push the empty cell in the list
    685.                         availableCells.Add(available);
    686.                     }
    687.                 }
    688.             }
    689.  
    690.             // get a random cell from the available cells
    691.             Vector2 chosenCell = availableCells[Random.Range(0,availableCells.Count)];
    692.             GameObject newTile = (GameObject)Instantiate (slider, gridToWorldPosition((int)chosenCell.x,(int)chosenCell.y), Quaternion.Euler (new Vector3(0,0,180)));
    693.             newTile.name = chosenCell.x + "_" + chosenCell.y;
    694.             newTile.GetComponent<Tile>().setValue(value);
    695.             newTile.transform.localScale= new Vector3(0,0,0);
    696.             // play the animation
    697.             newTile.GetComponent<TileAnimator>().entryAnimation();
    698.             grid[(int)chosenCell.x,(int)chosenCell.y] = value;
    699.  
    700.         }
    701.     }
    702.  
    703.  
    704.     //
    705.     // void resetGrid
    706.     //
    707.     // Mr. Proper...
    708.     // reset the grid
    709.     // clean the cells
    710.     // destroy tiles (GameObjects)
    711.     //
    712.  
    713.     public void resetGrid(){
    714.         // clear the grid (model)
    715.         for (int y = 0; y < SIZE; y++) {
    716.             for (int x = 0; x < SIZE; x++) {
    717.                 grid[x,y] = 0;
    718.             }
    719.         }
    720.         // eliminate the game Objects on the grid (view)
    721.         GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
    722.         foreach (GameObject tile in tiles) {
    723.             Destroy(tile);
    724.         }
    725.     }
    726.  
    727.  
    728.     //
    729.     // int findTarget
    730.     //
    731.     // check where the tiles can be moved after player input
    732.     //
    733.  
    734.     public int findTarget(int col, int rows, int stop) {
    735.         int target;
    736.         if (rows == 0){
    737.             return rows;
    738.         }
    739.         for (target = rows-1; target >= 0; target--) {
    740.             if (grid[col,target] != 0) {
    741.                 if (grid[col,target] != grid[col,rows]) {
    742.                     // merge is not possible,
    743.                     // take the next position
    744.                     return target+1;
    745.                 }
    746.                 return target;
    747.             }
    748.             else {
    749.                 // we should not slide further,
    750.                 // return this one
    751.                 if (target == stop) {
    752.                     return target;
    753.                 }
    754.             }
    755.         }
    756.         // we did not find a position
    757.         return rows;
    758.     }
    759.  
    760.  
    761.     //
    762.     // bool slideArray
    763.     //
    764.     // can the player move be executed
    765.     // and the tiles be moved in the intended direction
    766.     //
    767.  
    768.     public bool slideArray(int col, int rot) {
    769.         bool success = false;
    770.         int target;
    771.         int stopAtPosition=0;
    772.         bool merged = false;
    773.         // for each column, now iterate the complete row
    774.         for (int y = 0; y < SIZE; y++) {
    775.             // evaluate only, if grid cell is not empty
    776.             if (grid[col,y] != 0) {
    777.                 target = findTarget(col, y, stopAtPosition);
    778.                 // target is not the current grid cell
    779.                 // then move or merge
    780.                 if (target != y){
    781.                     // set stop variable to avoid double merge
    782.                     // 2,2,4,4 --> 4,8,0,0 and not
    783.                     // 2,2,4,4, --> 8,4,0,0
    784.                     if (grid[col,target]!=0) {
    785.                         score += grid[col,target] + grid[col,y];
    786.                         stopAtPosition = target + 1;
    787.                         merged = true;
    788.                     }
    789.                     // move the source cell to target position
    790.                     grid[col,target] += grid[col,y];
    791.  
    792.                     Vector2 targetPos = rotMatrix[rot, col, target];
    793.                     Vector2 sourcePos = rotMatrix[rot, col, y];
    794.                     GameObject tile = GameObject.Find(sourcePos.x+"_"+sourcePos.y);
    795.                     if (tile!=null)
    796.                     tile.GetComponent<TileAnimator>().setPosition(gridToWorldPosition((int)sourcePos.x,(int)sourcePos.y),
    797.                                                                       gridToWorldPosition((int)targetPos.x,(int)targetPos.y));
    798.  
    799.                     // clear the source cell
    800.                     grid[col,y] = 0;
    801.  
    802.                     success = true;
    803.                 }
    804.             }
    805.         }
    806.         return success;
    807.     }
    808.  
    809.  
    810.     //
    811.     // bool findPairs
    812.     //
    813.     // did we find equal tile in direct neighborhood
    814.     // after the player's move?
    815.     // (these will be merged)
    816.     //
    817.  
    818.     public bool findPairs() {
    819.         for (int y = 0;y < SIZE-1; y++) {
    820.             for (int x = 0;x < SIZE; x++) {
    821.                 if (grid[x,y]==grid[x,y+1])
    822.                     return true;
    823.             }
    824.         }
    825.         return false;
    826.     }
    827.  
    828.  
    829.     //
    830.     // bool gameEnded
    831.     //
    832.     // check if another move is possible
    833.     // if not, the game is over
    834.     //
    835.  
    836.     bool gameEnded() {
    837.         bool ended = true;
    838.         if (getCurrentTiles() < SIZE*SIZE) return false;
    839.         if (findPairs()) return false;
    840.         rotateBoard();
    841.         if (findPairs()) ended = false;
    842.         rotateBoard();
    843.         rotateBoard();
    844.         rotateBoard();
    845.         if (ended == true) Debug.Log("Game Over");
    846.         return ended;
    847.     }
    848.  
    849.  
    850.     //
    851.     // void rotateBoard
    852.     //
    853.     // as already discussed, a move to the right can be considered as
    854.     // a counterclockwise rotation about 90° and a move upwards
    855.     //
    856.     // this method rotates the board by 90°
    857.     //
    858.  
    859.     public void rotateBoard() {
    860.         for (int y = 0; y < SIZE/2; y++) {
    861.             for (int x = y; x < SIZE - y - 1; x++) {
    862.                 int tmp = grid[y,x];
    863.                 grid[y,x] = grid[x,SIZE-y-1];
    864.                 grid[x,SIZE-y-1] = grid[SIZE-y-1,SIZE-x-1];
    865.                 grid[SIZE-y-1,SIZE-x-1]=grid[SIZE-x-1,y];
    866.                 grid[SIZE-x-1,y]=tmp;
    867.             }
    868.         }
    869.     }
    870.  
    871.     //
    872.     // bool moveXY
    873.     //
    874.     // now see what I mean by considering th efollowing methods...
    875.     //
    876.  
    877.     public bool moveLeft() {
    878.         bool success;
    879.         rotateBoard();
    880.         success = moveUp(1);
    881.         rotateBoard();
    882.         rotateBoard();
    883.         rotateBoard();
    884.         return success;
    885.     }
    886.  
    887.     public bool moveRight() {
    888.         bool success;
    889.         rotateBoard();
    890.         rotateBoard();
    891.         rotateBoard();
    892.         success = moveUp(3);
    893.         rotateBoard();
    894.         return success;
    895.     }
    896.  
    897.     public bool moveUp(int rot) {
    898.         move++;
    899.         bool success = false;
    900.         // iterate each column
    901.         for (int x = 0; x < SIZE; x ++) {
    902.             success = success | slideArray(x, rot);
    903.         }
    904.         return success;
    905.     }
    906.  
    907.     public bool moveDown() {
    908.         bool success;
    909.         rotateBoard();
    910.         rotateBoard();
    911.         success = moveUp(2);
    912.         rotateBoard();
    913.         rotateBoard();
    914.         return success;
    915.     }
    916.    
    917.  
    918.     //
    919.     // void OnGUI
    920.     //
    921.     // this method is an unity event function and draws the GUI
    922.     //
    923.    
    924.     public void OnGUI(){
    925.         // try to calculate resolution independence
    926.         float rx = Screen.width / nativeWidth;
    927.         float ry = Screen.height / nativeHeight;
    928.            
    929.         GUI.matrix = Matrix4x4.TRS (new Vector3(0,0,0), Quaternion.identity, new Vector3 (rx, ry, 1));
    930.            
    931.         // Create own style for a GUI-Label
    932.         GUIStyle myLabelStyle = new GUIStyle(GUI.skin.label);
    933.         myLabelStyle.fontSize = 20;
    934.         myLabelStyle.fontStyle = FontStyle.Bold;
    935.         labelStyle.normal.textColor = Color.white;
    936.         labelStyle1.normal.textColor = Color.white;
    937.         GUI.Label(labelPosition, labelText, labelStyle);
    938.         GUI.Label(labelPosition1, labelText1, labelStyle1);
    939.  
    940.         // Create own style for a GUI-Label
    941.         GUIStyle myLabel2Style = new GUIStyle(GUI.skin.label);
    942.         myLabel2Style.fontSize = 80;
    943.         myLabel2Style.fontStyle = FontStyle.Bold;
    944.         myLabel2Style.normal.textColor = Color.blue;
    945.         //GUI.Label(new Rect (450,10,200,200),"Dots",myLabel2Style);
    946.  
    947.         //new game button
    948.         if (GUI.Button (labelPosition3,buttonTexture,labelStyle3)){
    949.             score = 0;
    950.             resetGrid();
    951.             gameState = GameStates.loaded;
    952.         }
    953.  
    954.         // if game ids over, display a message
    955.         if (gameState == GameStates.over) {
    956.             GUI.color = new Color(1,1,1,0.5f);
    957.             GUI.DrawTexture(new Rect(277,226,472,472), backgroundTexture);
    958.             GUI.color = new Color(1,1,1,1);
    959.             myLabel2Style.fontSize = 128;
    960.             myLabel2Style.normal.textColor = Color.gray;
    961.             GUI.Label(new Rect (320,310,400,300),"GAME OVER",myLabel2Style);
    962.             solver = false;
    963.             solver1 = false;
    964.         }
    965.  
    966.    
    967.         }
    968.    
    969.  
    970.     // ---------------------------------------------------------------
    971.     // ---------------------------------------------------------------
    972.     // ---------------------------------------------------------------
    973.  
    974.     // Attention, attention! now introducing: the 2048 AI
    975.  
    976.     // ---------------------------------------------------------------
    977.     // ---------------------------------------------------------------
    978.     // ---------------------------------------------------------------
    979.  
    980.     // even the AI is confronted with new random tiles generated each move...
    981.  
    982.     int[] MOVES = new int[2]{2,4};
    983.     double[] PROBABILITIES = new double[2]{0.9, 0.1};
    984.  
    985.     //
    986.     // void KI
    987.     //
    988.     // this is the main AI method
    989.     // called from the Update method
    990.     //
    991.     // it gets a reference to the game grid to work on
    992.     //
    993.  
    994.     public void KI(int[,] _grid) {
    995.         // get copy of game grid for KI mover
    996.         // as you can see, it's a "deep copy" - so it is no reference any more
    997.         // but an independent copy
    998.         int[,] myGrid = (int[,])_grid.Clone();
    999.         // evaluate the best move with a depth of 1
    1000.         // I'm using alpha-beta-pruning
    1001.         int direction = bestDirection(myGrid, (int)sliderDepth);
    1002.         // whatever move seems to be the best, it is executed
    1003.         switch (direction){
    1004.         case 0:
    1005.             movement = Movement.up;
    1006.             break;
    1007.         case 1:
    1008.             movement = Movement.right;
    1009.             break;
    1010.         case 2:
    1011.             movement = Movement.down;
    1012.             break;
    1013.         case 3:
    1014.             movement = Movement.left;
    1015.             break;
    1016.         }
    1017.  
    1018.     }
    1019.  
    1020.  
    1021.     //
    1022.     // int bestDirection
    1023.     //
    1024.     // this method evaluates the best move
    1025.     // depedent on the calculation depth
    1026.     //
    1027.  
    1028.     public int bestDirection(int[,] _grid, int depth) {
    1029.         // initialize bestScore and direction
    1030.         double bestScore = 0;
    1031.         int bestDir = -1;
    1032.  
    1033.         // iterate all directions
    1034.         for (int direction = 0; direction < 4; direction ++) {
    1035.             // make a copy of the grid - do not mess up the original game grid
    1036.             int[,] computerGrid = (int[,])_grid.Clone();
    1037.             moveKI(computerGrid, direction);
    1038.  
    1039.             // we did not find a move
    1040.             if (compareGrids(computerGrid, _grid)) {
    1041.             // so continue with next possible direction
    1042.                 continue;
    1043.             }
    1044.  
    1045.             // evaluate the computer move
    1046.             double computerScore = computerMove(computerGrid, 2*depth-1);
    1047.  
    1048.             // we did find a move (better than a preceding one)
    1049.             // so set the new move as the best one
    1050.             if (computerScore >= bestScore) {
    1051.                 bestScore = computerScore;
    1052.                 bestDir = direction;
    1053.             }
    1054.         }
    1055.         // return the best direction found so far
    1056.         return bestDir;
    1057.     }
    1058.  
    1059.  
    1060.     //
    1061.     // double computerMove
    1062.     //
    1063.     // computer move sets randomly a tile on the grid
    1064.     //
    1065.  
    1066.     public double computerMove(int[,] _grid, int _depth) {
    1067.  
    1068.         double totalScore = 0;
    1069.         double totalWeight = 0;
    1070.  
    1071.         // save the scores in a hashtable
    1072.         // for pruning the search tree
    1073.         Dictionary <string,double> hTable = new Dictionary<string, double>();
    1074.  
    1075.         // iterate the game grid
    1076.         for (int y = 0; y < SIZE; y++) {
    1077.             for (int x = 0; x < SIZE; x++) {
    1078.                 // if there is an empty spot on the grid,
    1079.                 // the computer may set a "2" or a "4"
    1080.                 if (_grid[x,y] == 0) {
    1081.                     // so iterate the possibilities
    1082.                     for (int i=0; i < 2; i++) {
    1083.                         // deep copy the grid to prepare the player move
    1084.                         int[,] playerGrid = (int[,])_grid.Clone();
    1085.                         // set value on the grid (2 or 4, respectively)
    1086.                         playerGrid[x,y] = MOVES[i];
    1087.  
    1088.                         // do the player move
    1089.                         double score = playerMove(playerGrid, _depth-1, hTable);
    1090.                         totalScore += PROBABILITIES[i]*score;
    1091.                         totalWeight += PROBABILITIES[i];
    1092.                     }
    1093.                 }
    1094.             }
    1095.         }
    1096.         return totalWeight == 0 ? 0 : totalScore/totalWeight;
    1097.     }
    1098.  
    1099.  
    1100.     //
    1101.     // double playerMove
    1102.     //
    1103.     // it may sound kind of schizo (gollum.... gollum...)
    1104.     // the computer is switching personality. it now does a computation
    1105.     // "which move could the player have done to do the most impact on me..."
    1106.     //
    1107.  
    1108.     public double playerMove(int[,] _grid, int _depth, Dictionary<string,double> _htable) {
    1109.  
    1110.         // is the end of recusrion reached?
    1111.         if (_depth == 0) {
    1112.             return hasMove(_grid) ? evaluateHeuristic(_grid) : 0;
    1113.         }
    1114.  
    1115.         double bestScore = 0;
    1116.  
    1117.         for (int direction = 0; direction < 4; direction++) {
    1118.             int[,] computerGrid = (int[,])_grid.Clone();
    1119.             moveKI (computerGrid,direction);
    1120.  
    1121.             if (compareGrids(computerGrid, _grid)) {
    1122.                 continue;
    1123.             }
    1124.  
    1125.             double computerScore = 0;
    1126.  
    1127.             // ok. did we already measure the grid?
    1128.             // then there must be an entry in the hastable
    1129.             if (_htable.ContainsKey(calcHash(computerGrid))) {
    1130.                 computerScore = _htable[calcHash(computerGrid)];
    1131.             }
    1132.             // no score stored
    1133.             // so let's do some backtracking
    1134.             else {
    1135.                 computerScore = computerMove(computerGrid, _depth-1);
    1136.                 _htable.Add(calcHash(computerGrid),computerScore);
    1137.             }
    1138.  
    1139.             if (computerScore > bestScore) {
    1140.                 bestScore = computerScore;
    1141.             }
    1142.         }
    1143.         return bestScore;
    1144.     }
    1145.    
    1146.  
    1147.     //
    1148.     // bool hasMove
    1149.     //
    1150.     // can the computer still make a move?
    1151.     //
    1152.    
    1153.     public bool hasMove(int[,] _grid) {
    1154.         // iterate the grid
    1155.         for (int x = 0; x < 4; x++)
    1156.         {
    1157.             for (int y = 0; y < 4; y++)
    1158.             {
    1159.                 // are there empty spots on the grid?
    1160.                 if (_grid[x,y]== 0)
    1161.                     return true;
    1162.                 // are there neighboring cells with same value?
    1163.                 if (x < 3 && _grid[x,y] == _grid[x+1,y])
    1164.                     return true;
    1165.                 if (y < 3 && _grid[x,y] == _grid[x,y+1])
    1166.                     return true;
    1167.             }
    1168.         }
    1169.         // nothing found so far
    1170.         return false;
    1171.     }
    1172.  
    1173.  
    1174.     //
    1175.     // to see which move is the best one, we need a
    1176.     // weighting function
    1177.     //
    1178.  
    1179.     int[,,] weight_matrices = new int[2,4,4]{
    1180.         {
    1181.             { 3, 2, 1,  0},
    1182.             { 2, 1, 0,  -1},
    1183.             { 1, 0, -1,  -2},
    1184.             { 0, -1, -2,  -3}
    1185.         },
    1186.         {
    1187.             { 0, 1, 2, 3},
    1188.             { -1, 0, 1, 2},
    1189.             { -2, -1, 0, 1},
    1190.             { -3, -2, -1, 0}
    1191.         }
    1192.     };
    1193.  
    1194.  
    1195.     //
    1196.     // int evaluateHeuristic
    1197.     //
    1198.     // each move done is evaluated, given a hash value and stored in
    1199.     // a hastable
    1200.     //
    1201.  
    1202.     public int evaluateHeuristic(int[,] _grid) {
    1203.         // store the best heuristic move
    1204.         int best = 0;
    1205.         // we have two matrices to check
    1206.         for (int i = 0; i < 2; i++){
    1207.             int s = 0;
    1208.             // iterate the grid
    1209.             for (int y = 0; y < 4; y++)
    1210.             {
    1211.                 for (int x = 0; x < 4; x++)
    1212.                 {
    1213.                     s += weight_matrices[i,y,x] * _grid[x,y];
    1214.                 }
    1215.             }
    1216.             s = Mathf.Abs(s); // Hack for symmetry
    1217.             // did we find a new best
    1218.             if (s > best)
    1219.             {
    1220.                 best = s;
    1221.             }
    1222.         }
    1223.         return best;
    1224.     }
    1225.  
    1226.  
    1227.     //
    1228.     // void moveKI
    1229.     //
    1230.     // AI is making a move
    1231.     //
    1232.  
    1233.     void moveKI(int[,] _grid, int direction)
    1234.     {
    1235.         switch (direction){
    1236.         case 0:
    1237.             shift_up(_grid);
    1238.             break;
    1239.         case 1:
    1240.             shift_right(_grid);
    1241.             break;
    1242.         case 2:
    1243.             shift_down(_grid);
    1244.             break;
    1245.         case 3:
    1246.             shift_left(_grid);
    1247.             break;
    1248.         }
    1249.     }
    1250.  
    1251.  
    1252.     void shift_up(int[,] _grid)
    1253.     {
    1254.         for (int column = 0; column < 4; column++)
    1255.         {
    1256.             int[] cells = new int[4];
    1257.             for (int y = 0; y < 4; y++)
    1258.             {
    1259.                 cells[y] = _grid[column,y];
    1260.             }
    1261.             moveCells(cells);
    1262.             for (int y = 0; y < 4; y++)
    1263.             {
    1264.                 _grid[column,y] = cells[y];
    1265.             }
    1266.         }
    1267.     }
    1268.    
    1269.     void shift_down(int[,] _grid)
    1270.     {
    1271.         for (int column = 0; column < 4; column++)
    1272.         {
    1273.             int[] cells = new int[4];
    1274.             for (int y = 0; y < 4; y++)
    1275.             {
    1276.                 cells[y] = _grid[column, 3-y];
    1277.             }
    1278.             moveCells(cells);
    1279.             for (int y = 0; y < 4; y++)
    1280.             {
    1281.                 _grid[column, 3-y] = cells[y];
    1282.             }
    1283.         }
    1284.     }
    1285.    
    1286.     void shift_left(int[,] _grid)
    1287.     {
    1288.         for (int row = 0; row < 4; row++)
    1289.         {
    1290.             int[] cells = new int[4];
    1291.             for (int x = 0; x < 4; x++)
    1292.             {
    1293.                 cells[x] = _grid[x,row];
    1294.             }
    1295.             moveCells(cells);
    1296.             for (int x = 0; x < 4; x++)
    1297.             {
    1298.                 _grid[x,row] = cells[x];
    1299.             }
    1300.         }
    1301.     }
    1302.    
    1303.     void shift_right(int[,] _grid)
    1304.     {
    1305.         for (int row = 0; row < 4; row++)
    1306.         {
    1307.             int[] cells = new int[4];
    1308.             for (int x = 0; x < 4; x++)
    1309.             {
    1310.                 cells[x] = _grid[3-x,row];
    1311.             }
    1312.             moveCells(cells);
    1313.             for (int x = 0; x < 4; x++)
    1314.             {
    1315.                 _grid[3-x, row] = cells[x];
    1316.             }
    1317.         }
    1318.     }
    1319.  
    1320.     void moveCells(int[] cells) {
    1321.         int target = 0;
    1322.         for (int i = 1; i < 4; i++)
    1323.         {
    1324.             int targetValue = cells[target];
    1325.             int currentValue = cells[i];
    1326.             if (currentValue != 0){
    1327.                 if (targetValue == 0){
    1328.                     cells[target] = currentValue;
    1329.                     cells[i] = 0;
    1330.                 }
    1331.                 else{
    1332.                     if (targetValue == currentValue){
    1333.                         cells[i] = 0;
    1334.                         cells[target] <<= 1;
    1335.                     }
    1336.                     else{
    1337.                         cells[i] = 0;
    1338.                         cells[target + 1] = currentValue;
    1339.                     }
    1340.                     target++;
    1341.                 }
    1342.             }
    1343.         }
    1344.     }
    1345.  
    1346.  
    1347.     //
    1348.     // bool compareGrids
    1349.     //
    1350.     // during evaluation, the computer may find a lot of possible grids
    1351.     // as a result of a valid move
    1352.     // we check whether the found grid is already known to possibly cut of
    1353.     // the search tree
    1354.     //
    1355.  
    1356.     public bool compareGrids(int[,] grid1, int[,] grid2) {
    1357.         for (int y = 0; y < SIZE; y ++) {
    1358.             for (int x = 0; x < SIZE; x ++) {
    1359.                 if (grid1[x,y]  != grid2[x,y])
    1360.                     return false;
    1361.             }
    1362.         }
    1363.         return true;
    1364.     }
    1365.  
    1366.  
    1367.     //
    1368.     // string calchash
    1369.     //
    1370.     // each grid is given an individual hash
    1371.     // consisting of position and value of the tiles
    1372.     //
    1373.     // this hash helps to find possible multiple moves
    1374.     //
    1375.  
    1376.     public string calcHash(int[,] _grid) {
    1377.         long h = 2166136261;
    1378.         for (int y = 0; y < SIZE; y ++) {
    1379.             for (int x = 0;x< SIZE;x++) {
    1380.                 h = h ^ (_grid[x,y] * 16777619);
    1381.             }
    1382.         }
    1383.         return h.ToString();
    1384.     }
    1385.  
    1386.     public int highestTile(int[,] _grid) {
    1387.         int h = 0;
    1388.         for (int y = 0; y < SIZE; y ++) {
    1389.             for (int x = 0;x< SIZE;x++) {
    1390.                 if (_grid[x,y] > h)
    1391.                     h = _grid[x,y];
    1392.             }
    1393.         }
    1394.         return h;
    1395.     }
    1396.     public void onClick()
    1397.     {
    1398.            
    1399.             score = 0;
    1400.             resetGrid();
    1401.             gameState = GameStates.loaded;
    1402.                    
    1403.     }
    1404. }
    1405.  
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    To clarify, because I'm not understanding the problem exactly- which combination of the following is your issue?
    1. Every GameObject is responding to / being controlled by a press regardless of where the press occurs
    2. The coordinates where you press do not match up to the raycast position being sent into the game world
    3. Raycasts are still firing into the game world even when UI elements are being pressed
    4. You wanted to restrict the "raycast on press" area to some small arbitrarily-set region of the screen and that restriction isn't being followed
    Also, this script is massive. Is there any chance at all you can dumb it down and/or cut out portions that you don't believe have anything to do with this? Leave the whole script where it is, just post the "shortened" version as new, if possible.
     
  3. shawnrevels

    shawnrevels

    Joined:
    Aug 13, 2014
    Posts:
    86
    I attached a picture of what i mean. I want the green cross area to be swipable or clickable. The red are to not be toucbable. Although i want to add a drop down combo menu at the top somewhere. The game is a swipe type game. Swipe a color and it collides with another of the same color and the player gets points. Something along those lines. Here is the code that holds the ontouch and onlclick actions.

    Code (CSharp):
    1. void checkSwipeTouch() {
    2.      
    3.         if (Input.touches.Length > 0)
    4.         {
    5.             Touch t = Input.GetTouch(0);
    6.             if(t.phase == TouchPhase.Began) {
    7.              
    8.                 //save began touch 2d point
    9.                 firstPressPos = new Vector2(t.position.x,t.position.y);
    10.             }
    11.             if (t.phase == TouchPhase.Ended) {
    12.                 //save ended touch 2d point
    13.                 secondPressPos = new Vector2(t.position.x,t.position.y);
    14.              
    15.                 //create vector from the two points
    16.                 currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    17.              
    18.                 //normalize the 2d vector
    19.                 currentSwipe.Normalize();
    20.              
    21.                 //swipe upwards
    22.                 if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    23.                     movement = Movement.up;
    24.                 }
    25.                 //swipe down
    26.                 if(currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    27.                     movement = Movement.down;
    28.                 }
    29.                 //swipe left
    30.                 if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    31.                     movement = Movement.left;
    32.                 }
    33.                 //swipe right
    34.                 if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f){
    35.                     movement = Movement.right;
    36.                 }
    37.             }
    38.         }
    39.     }
    40.     void checkSwipeClick() {
    41.         if(Input.GetMouseButtonDown(0))
    42.         {
    43.             //save began touch 2d point
    44.             firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    45.         }
    46.         if(Input.GetMouseButtonUp(0))
    47.         {
    48.             //save ended touch 2d point
    49.             secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    50.          
    51.             //create vector from the two points
    52.             currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    53.          
    54.             //normalize the 2d vector
    55.             currentSwipe.Normalize();
    56.          
    57.             //swipe upwards
    58.             if(currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
    59.             {
    60.                 movement = Movement.up;
    61.             }
    62.             //swipe down
    63.             if(currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f)
    64.             {
    65.                 movement = Movement.down;
    66.             }
    67.             //swipe left
    68.             if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
    69.             {
    70.                 movement = Movement.left;
    71.             }
    72.             //swipe right
    73.             if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f)
    74.             {
    75.                 movement = Movement.right;
    76.             }
    77.         }
    78.     }
    79.     //
    80.     // Vector2 worldToGridPosition
    81.     //
    82.     // this method converts input-positions on the screen to game-grid positions
    83.     //
    and this is the code that holds the grid where the game objects are cloned into the grid itself. It uses raycast.

    Code (CSharp):
    1. //
    2.     // Vector2 worldToGridPosition
    3.     //
    4.     // this method converts input-positions on the screen to game-grid positions
    5.     //
    6.     public Vector2 worldToGridPosition(Vector3 position) {
    7.         Vector2 gridPosition = new Vector2();
    8.         gridPosition.x = (position.x - horizontalSpacing)/(tileSize+spacing);
    9.         gridPosition.y = -(position.y - verticalSpacing)/(tileSize+spacing);
    10.         return gridPosition;
    11.     }
    12.     //
    13.     // Vector3 gridToWorldPosition
    14.     //
    15.     // convert grid Position to position on the screen
    16.     // --> world position
    17.     //
    18.     public Vector3 gridToWorldPosition(int x, int y){
    19.         return new Vector3(horizontalSpacing+(tileSize+spacing)*x,verticalSpacing-(tileSize+spacing)*y,-0.2f);
    20.     }
    21.     //
    22.     // GameObject getObjectAtGridPosition
    23.     //
    24.     // use a Raycast to check the actual grid position
    25.     // for a gameObject
    26.     //
    27.     public GameObject getObjectAtGridPosition(int x, int y) {
    28.         RaycastHit hit;
    29.         // get the current world position
    30.         Vector3 gridPosition = gridToWorldPosition(x,y);
    31.         // step back from the object, so we can shoot a ray
    32.         // (otherwise, it will hit the cell container or the background)
    33.         gridPosition.z -= 0.2f;
    34.         // cast a ray and see if we hit something
    35.         if (Physics.Raycast(gridPosition, new Vector3(0,0,1),out hit))
    36.         {
    37.             // is the GameObject found a tile?
    38.             Tile tile = hit.collider.GetComponent<Tile>();
    39.             // then return the gameObject found at position (x,y)
    40.             if (tile != null)
    41.                 return hit.collider.gameObject;
    42.         }
    43.         // sorry, we did not find an gameObject
    44.         return null;
    45.     }
    46.  
     

    Attached Files:

  4. shawnrevels

    shawnrevels

    Joined:
    Aug 13, 2014
    Posts:
    86
    The problem is that where ever i touch, being inside the green area or the red area the colors move. I only want it swipable inside the green area.
     
  5. shawnrevels

    shawnrevels

    Joined:
    Aug 13, 2014
    Posts:
    86
    here is an actual picture of my game to clarify
     

    Attached Files:

  6. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    I don't see any conditionals that have to do with touch regions (unless I'm blind)- you should define an area in either Screen coordinates or Viewport coordinates (my strong preference) that allow for swipes.

    You can do this in one of two easy ways that my sleep-deprived brain can currently conjure. The first is to make the input controller take care of whether or not the input is acceptable, and the second is to accept the input regardless and let some other method in your script handle whether the resulting positional data is usable. I went with the former in my own code, as it cuts down on processing the earlier you can stop an "illegal input", and leaves less room for errors. You seem to have gone for the third option of not having acceptable inputs but rather acceptable targets. I'd have a tough time debugging that kind of thing...

    In the former method, you'd essentially just check if the firstPressPosition is within the bounds you've set in screen space- and if it isn't, then don't even bother recording it, or better yet record it as Vector2.zero. Have the followup for the "ended" conditional check if the first position is Vector2.zero and skip that part too if it is. That way the input never even makes it into your game.

    You might also want to put in a mid-drag update check and force the drag to end when it runs outside of the border of your "play area".
     
    shawnrevels likes this.
  7. cybertree

    cybertree

    Joined:
    Jun 19, 2015
    Posts:
    100
    well il do something like this.
    Code (CSharp):
    1. private float oldx;
    2. private float oldy;
    3.  
    4.  
    5. void Update() {
    6.     oldx = transform.position.x;
    7.     oldy = transform.position,y;
    8.  
    9. if (clickinthemenu) {
    10.     transform.position = new Vector2 ( oldx, oldy);
    11. }
    12.  
    13.  
    im not sure if this will work but I'm a bit of a noob