Search Unity

Is there a way to simulate the Touch using the mouse?

Discussion in 'iOS and tvOS' started by sabater_wb, Jul 19, 2010.

  1. sabater_wb

    sabater_wb

    Joined:
    Jul 19, 2010
    Posts:
    1
    I installed Unity Iphone to try, but I don't have an Iphone yet.
    I oppened the penelope tutorial and tryed to play in the unity. But it didn't workt because there is no way to simulate a touch. I changed a piece of code and them I could go to the next screen where I can choose the camera type.

    I would like to try, using the mouse. Can someone give me some tip ?
     
  2. defjr

    defjr

    Joined:
    Apr 27, 2009
    Posts:
    436
    Have you tried the iPhone simulator?
     
  3. Bulgroz

    Bulgroz

    Joined:
    Oct 19, 2007
    Posts:
    49
    Well

    If you stick to the "Input.GetMouseButtonDown" set of functions, then you can use your mouse in the editor Game window to act as replacements for touches, if thats what your after.

    file:///Applications/Unity%20iPhone/Documentation/ScriptReference/Input.GetMouseButtonDown.html

    these works as (are translated to) touch events on iDevices.

    /Chris
     
  4. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    Unity does not support the simulator for its builds.

    "simulating touch" is done through the remote, thats much more direct and really multitouch unlike the simulator
     
    Nebulaxin and SibochCZ like this.
  5. defjr

    defjr

    Joined:
    Apr 27, 2009
    Posts:
    436
    Can you install unity remote on the simulator though?
     
  6. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    that you can do.

    but the simulator has no multitouch aside of its fake multitouch and also no accelerometer.
     
  7. nvarcha

    nvarcha

    Joined:
    Sep 27, 2008
    Posts:
    191
    You can do something like this:

    Code (csharp):
    1.  
    2. var touchPos : Vector2;
    3. var aTouch : boolean = false;
    4.  
    5. if (Application.platform != RuntimePlatform.IPhonePlayer)
    6. {
    7.   // use the input stuff
    8.   aTouch = Input.GetMouseButton(0);
    9.   touchPos = Input.mousePosition;
    10. } else {
    11.   // use the iPhone Stuff
    12.   aTouch = (iPhoneInput.touchCount > 0);
    13.   touchPos = iPhoneInput.touches[0].position;
    14. }
    15.  
    (I didn't test the code).

    Hope this helps.
     
    Otavio_ and jimrota like this.
  8. criistii22

    criistii22

    Joined:
    Jan 18, 2011
    Posts:
    52
    Probably a bit late, but i modified the default Joystick.js script, so it accepts also mouse input, based on nvarcha's tip, hope it helps others:

     
  9. paulygons

    paulygons

    Joined:
    May 6, 2010
    Posts:
    164
    OK, if I understood the joystick script correctly (I haven't tried to set it up yet), you're using a literal joystick to fake touch events within the editor, for testing. If so, that's just crazy brilliant, and you are a god. Otherwise, whatever you're doing here is above my understanding, which pretty much still makes you some kind of minor deity at least...
     
  10. bryanleister

    bryanleister

    Joined:
    Apr 28, 2009
    Posts:
    130
    Thanks! This was helpful, here's a version of the original Joystick.js in C# for those interested along with the added code for editor mouse input.

    Oh, there's also a little bit of code to position the joystick elements for iPhone or iPad...

    Code (csharp):
    1.  
    2. // Joystick.js - Converted to C# - JoyStick.cs by Bryan Leister
    3. // with some additional code for using Editor mouseinput based on Criistii
    4. // Penelope iPhone Tutorial
    5. //
    6. // Joystick creates a movable joystick (via GUITexture) that
    7. // handles touch input, taps, and phases. Dead zones can control
    8. // where the joystick input gets picked up and can be normalized.
    9. //
    10. // Optionally, you can enable the touchPad property from the editor
    11. // to treat this Joystick as a TouchPad. A TouchPad allows the finger
    12. // to touch down at any point and it tracks the movement relatively
    13. // without moving the graphic
    14. //////////////////////////////////////////////////////////////
    15.  
    16. using UnityEngine;
    17. using System.Collections;
    18.  
    19. public class ButtonBoundary
    20. {
    21.     public Vector2 min = Vector2.zero;
    22.     public Vector2 max = Vector2.zero;
    23. }
    24.  
    25. public class JoyStick : MonoBehaviour
    26. {
    27.     static private JoyStick[]   joysticks;                                                                  //a static collection of all joysticks
    28.     static private bool         enumeratedJoySticks     = false;
    29.     static private float        tapTimeDelta            = 0.3f;                                             //Time allowed between taps
    30.    
    31.     #region Public variables
    32.     public  bool                touchPad;                                                                   //is this a TouchPad?
    33.     public  Rect                touchZone;
    34.     public  Vector2             deadZone                = Vector2.zero;                                     //Control when position is output
    35.     public  bool                normalize;                                                                  //Normalize output after the deadzone?
    36.     public  Vector2             position;                                                                   //[ -1, 1 ] in x,y
    37.     public  int                 tapCount;                                                                   //current tap count                
    38.     #endregion
    39.    
    40.     #region Private variables
    41.     private int                 lastFingerId            = -1;                                               //Finger last used for this joystick
    42.     private float               tapTimeWindow;                                                              //How much time is there left for a tap to occur?
    43.     private Vector2             fingerDownPos;
    44. //  private float               fingerDownTime;
    45. //  private float               firstDeltaTime          = .5F;
    46.    
    47.     private GUITexture          gui;                                                                        //Joystick graphic
    48.     private Rect                defaultRect;                                                                //Default position/ extents of the joystick graphic
    49.     private ButtonBoundary      guiButtonBoundary           = new ButtonBoundary();                         //Boundary for joystick graphic
    50.     private Vector2             guiTouchOffset;                                                             //Offset to apply to touch input
    51.     private Vector2             guiCenter;                                                                  //center of joystick
    52.     #endregion
    53.    
    54.     public void Start ()
    55.     {
    56.         gui = (GUITexture)GetComponent( typeof(GUITexture) );                                               // Cache this component at startup instead of looking up every frame
    57.        
    58.         if( gui.pixelInset.x > Screen.width/2  )                                                            //If this is a left button, it should be set in the inspector to a high number (800+),
    59.         {                                                                                                   // if so, we will check that and position it according to display resolution of the device.
    60.                                                                                                             //For convenience, I've positioned it offset by the same # I have used for the Y offset
    61.             gui.pixelInset = new Rect((Screen.width - gui.pixelInset.width) - gui.pixelInset.y ,            //This may not work for all interfaces...
    62.                                       gui.pixelInset.y, gui.pixelInset.width, gui.pixelInset.height);
    63.         }
    64.        
    65.         defaultRect = gui.pixelInset;                                                                       // Store the default rect for the gui, so we can snap back to it
    66.    
    67.         defaultRect.x += transform.position.x * Screen.width;                                               // + gui.pixelInset.x; // -  Screen.width * 0.5;
    68.         defaultRect.y += transform.position.y * Screen.height;                                              // - Screen.height * 0.5;
    69.        
    70.         transform.position = new Vector3(0,0,transform.position.z);
    71.  
    72.         if ( touchPad )
    73.         {
    74.             if ( gui.texture )                                                                              // If a texture has been assigned, then use the rect ferom the gui as our touchZone
    75.                 touchZone = defaultRect;
    76.         }
    77.         else
    78.         {
    79.             guiTouchOffset.x = defaultRect.width * 0.5f;                                                    //This is an offset for touch input to match with the top left corner of GUI
    80.             guiTouchOffset.y = defaultRect.height * 0.5f;
    81.            
    82.             guiButtonBoundary.min.x = defaultRect.x - guiTouchOffset.x;                                         //Let's build the GUI boundary so we can clamp joystick movement
    83.             guiButtonBoundary.max.x = defaultRect.x + guiTouchOffset.x;
    84.             guiButtonBoundary.min.y = defaultRect.y - guiTouchOffset.y;
    85.             guiButtonBoundary.max.y = defaultRect.y + guiTouchOffset.y;
    86.            
    87.             guiCenter.x = defaultRect.x + guiTouchOffset.x;                                                 //Cache the center of the GUI, since it doesn't change
    88.             guiCenter.y = defaultRect.y + guiTouchOffset.y;
    89.         }
    90.     }
    91.    
    92.     public void Disable()
    93.     {
    94.         gameObject.active = false;
    95.         enumeratedJoySticks = false;
    96.     }
    97.  
    98.     public void ResetJoystick()
    99.     {
    100.         gui.pixelInset = defaultRect;                                                                       //Release the finger control and set the joystick back to the default position
    101.         lastFingerId = -1;
    102.         position = Vector2.zero;
    103.         fingerDownPos = Vector2.zero;
    104.        
    105.         if ( touchPad )                                                    
    106.             gui.color = new Color(gui.color.r, gui.color.g, gui.color.b, .25F);                             //make the touchpad semi-transparent on Reset
    107.        
    108.     }
    109.    
    110.     public bool IsFingerDown()                                                                              //is this joystick being pressed? Accessible from other scripts...
    111.     {
    112.         return ( lastFingerId != -1);
    113.     }
    114.    
    115.     public void LatchedFinger( int fingerId )
    116.     {
    117.         if( lastFingerId == fingerId )                                                                      //if another joystick has latched this finger, then we must release it
    118.         {
    119.                 ResetJoystick();
    120.         }
    121.     }
    122.    
    123.    
    124.     public void Update ()
    125.     {      
    126.         if( !enumeratedJoySticks )
    127.         {
    128.             joysticks = (JoyStick[]) FindObjectsOfType( typeof(JoyStick) );                                 // Collect all joysticks in the game, so we can relay finger latching messages
    129.             enumeratedJoySticks = true;
    130.         }
    131.        
    132.         int count = 0;
    133.         //int count = Input.touchCount;
    134.        
    135. #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER                                         //setting this up for Editor use
    136.        
    137.         if(Input.GetMouseButton(0))
    138.             {
    139.             count = 1;
    140.                 //Debug.Log("Mouse button: " + count);
    141.             }
    142. #else
    143.             count = Input.touchCount;
    144. #endif
    145.  
    146.        
    147.         if( tapTimeWindow > 0 )                                                                             // Adjust the tap time window while it still available
    148.         {
    149.             tapTimeWindow -= Time.deltaTime;
    150.         }
    151.         else
    152.         {
    153.             tapCount = 0;
    154.         }
    155.        
    156. #region Begin Touch detecting
    157.         if( count == 0 )                                                                                    // no fingers are touching, so we reset the position
    158.         {
    159.                 ResetJoystick();        
    160.         }
    161.         else
    162.         {
    163.             int fingerID;
    164.            
    165.            for( int i = 0; i < count; i++)
    166.            {
    167.                     Touch touch;
    168.  
    169.                
    170. #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER                     //Switch to use Editor for testing mouse input
    171.                
    172.                     Vector2 mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    173.                     Vector2 guiTouchPos = mousePos - guiTouchOffset;
    174.                     fingerID = 1;
    175.                     Vector2 touchPosition = Input.mousePosition;
    176. #else              
    177.                     touch = Input.GetTouch(i);
    178.                     Vector2 touchPosition = touch.position;                
    179.                     Vector2 guiTouchPos = touchPosition - guiTouchOffset;
    180.                     fingerID = touch.fingerId;             
    181. #endif
    182.                
    183.                 bool    shouldLatchFinger = false;
    184.                 if ( touchPad )
    185.                 {
    186.                     if ( touchZone.Contains( touchPosition ) )
    187.                     {
    188.                         shouldLatchFinger = true;
    189.                     }
    190.                 }
    191.                 else if (gui.HitTest( touchPosition ))
    192.                 {
    193.                     shouldLatchFinger = true;
    194.                 }
    195.                    
    196.                 if ( shouldLatchFinger  ( lastFingerId == -1 || lastFingerId != fingerID ) )        // Latch the finger if this is a new touch
    197.                 {
    198.                     if ( touchPad )
    199.                     {
    200.                         gui.color = new Color(gui.color.r, gui.color.g, gui.color.b, 1.0F);                 //Set the touchpad to fully opaque
    201.                         lastFingerId = fingerID;       
    202.                         fingerDownPos = touchPosition;                                                      //Record the down touch position
    203.                         //fingerDownTime = Time.time;                                                           //Record the time when it was touched down
    204.                     }
    205.                    
    206.                     lastFingerId = fingerID;
    207.                    
    208.                     if ( tapTimeWindow > 0 )                                                                // Accumulate taps if it is within the time window
    209.                         tapCount++;
    210.                     else
    211.                     {
    212.                         tapCount = 1;
    213.                         tapTimeWindow = tapTimeDelta;
    214.                     }
    215.                                                
    216.                     foreach ( JoyStick j in joysticks )                                                     // Tell other joysticks we've latched this finger
    217.                     {
    218.                         if ( j != this )
    219.                             j.LatchedFinger( fingerID );
    220.                     }
    221.                 }
    222.                                        
    223.                 if ( lastFingerId == fingerID )
    224.                 {  
    225.                    
    226.                     if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android) //If we are are on the actual device
    227.                     {
    228.                         touch = Input.GetTouch(i);
    229.                         if ( touch.tapCount > tapCount )                                                        // Override the tap count with what the iPhone SDK reports if it is greater
    230.                         {                                                                                       // This is a workaround, since the iPhone SDK does not currently track taps
    231.                                 tapCount = touch.tapCount;                                                      // for multiple touches
    232.                         }
    233.                     }
    234.                     if ( touchPad )                                                                             // For a touchpad, let's just set the position directly based on distance from initial touchdown
    235.                     {  
    236.                         position.x = Mathf.Clamp( ( touchPosition.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
    237.                         position.y = Mathf.Clamp( ( touchPosition.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
    238.                     }
    239.                     else
    240.                     {                  
    241.                         Rect r = gui.pixelInset;
    242.                         r.x =  Mathf.Clamp( guiTouchPos.x, guiButtonBoundary.min.x, guiButtonBoundary.max.x );  // Change the location of the joystick graphic to match where the touch is
    243.                         r.y =  Mathf.Clamp( guiTouchPos.y, guiButtonBoundary.min.y, guiButtonBoundary.max.y ); 
    244.                         gui.pixelInset = r;
    245.                     }
    246. #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER                             //Set up to use the Mouse while in the Editor
    247.  
    248.                     if( !Input.GetMouseButton(0))
    249.                     {
    250.                         ResetJoystick();
    251.                     }
    252. #else
    253.                     if ( touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled )
    254.                     {
    255.                         ResetJoystick();                                       
    256.                     }
    257. #endif
    258.                 }
    259.             }
    260.         }
    261.        
    262. #endregion
    263.    
    264.         if ( !touchPad )
    265.         {
    266.             position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;      // Get a value between -1 and 1 based on the joystick graphic location
    267.             position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;
    268.         }
    269.  
    270.         float absoluteX = Mathf.Abs( position.x );                                                      // Adjust for dead zone
    271.         float absoluteY = Mathf.Abs( position.y );
    272.        
    273.         if ( absoluteX < deadZone.x )                                                                   // Report the joystick as being at the center if it is within the dead zone
    274.         {
    275.             position.x = 0;
    276.         }
    277.         else if ( normalize )                                                                           // Rescale the output after taking the dead zone into account
    278.         {
    279.             position.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );
    280.         }
    281.            
    282.         if ( absoluteY < deadZone.y )                                                                   // Report the joystick as being at the center if it is within the dead zone
    283.         {
    284.             position.y = 0;
    285.         }
    286.         else if ( normalize )                                                                           // Rescale the output after taking the dead zone into account
    287.         {
    288.             position.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );
    289.         }
    290.     }
    291. }
    292.  
    293.  
     
    Last edited: Aug 11, 2011
  11. stoli

    stoli

    Joined:
    Nov 13, 2012
    Posts:
    4
    After replacing the joystick.js file it makes no difference for me, clicking dosent work. I am doing 3d modelling and would like to use this project with my own modells. I have not much experience in programming so maybe i am doing something wrong or did anyone else get the script working ?

    I am trying to use the javascript one.
     
    Last edited: Nov 13, 2012
  12. stoli

    stoli

    Joined:
    Nov 13, 2012
    Posts:
    4
    Actually it does work, its just the beginning where it says "touch to start" which dosent work. the joystics work fine.
     
  13. Richard-3

    Richard-3

    Joined:
    Jul 19, 2012
    Posts:
    2
    The updated joystick script works great. I'm using it on a Lenova with a touch screen. Any ideas on how I would go about multi touches at the same time. The Lenova accepts up to ten touches at once. At this point I can either look around or walk around separately, not at the same time.
     
  14. smallbit

    smallbit

    Joined:
    Oct 3, 2013
    Posts:
    60
    I have faced some problems saying that class name doesn't match the filename. For some reason the file name was changing from JoyStick to Joystick that caused problems, I renamed all instances in script itself to Joystick and works as a charm except weird behavior. What i mean is that Joystick moves automatically wherever i click on it generating output(in my case camera rotation) instantly. For instance if I touch the screen somewhere on the left side of the rectangle Joystick moves directly here like If I dragged it from the center to this position, I would prefer it to start moving from the center wherever I anchor my finger.

    @Richard3 you must count the touches here is a tutorial for that (http://www.youtube.com/watch?v=uUIXFL2ic7k&list=PLXiP0AQLyreL9hEuqQ0BqEH0i4WQgcsFa&index=3)
     
  15. KyryloKuzyk

    KyryloKuzyk

    Joined:
    Nov 4, 2013
    Posts:
    1,144
    There is no simple solution to this problem. The cleanest solution I came up with is to write a wrapper around UnityEngine.Input class. I implemented only the most common functions, but you can add your own at any time.

    To use it, add this line on top of your script that uses UnityEngine.Input:
    Code (CSharp):
    1. using Input = InputWrapper.Input;
    Source code:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Assertions;
    3.  
    4. namespace InputWrapper {
    5.     public static class Input {
    6.         public static bool GetButton(string buttonName) {
    7.             return UnityEngine.Input.GetButton(buttonName);
    8.         }
    9.  
    10.         public static bool GetButtonDown(string buttonName) {
    11.             return UnityEngine.Input.GetButtonDown(buttonName);
    12.         }
    13.  
    14.         public static bool GetButtonUp(string buttonName) {
    15.             return UnityEngine.Input.GetButtonUp(buttonName);
    16.         }
    17.  
    18.         public static bool GetMouseButton(int button) {
    19.             return UnityEngine.Input.GetMouseButton(button);
    20.         }
    21.  
    22.         public static bool GetMouseButtonDown(int button) {
    23.             return UnityEngine.Input.GetMouseButtonDown(button);
    24.         }
    25.  
    26.         public static bool GetMouseButtonUp(int button) {
    27.             return UnityEngine.Input.GetMouseButtonUp(button);
    28.         }
    29.  
    30.         public static int touchCount {
    31.             get {
    32. #if UNITY_EDITOR
    33.                 return fakeTouch.HasValue ? 1 : 0;
    34. #else
    35.                 return UnityEngine.Input.touchCount;
    36. #endif
    37.             }
    38.         }
    39.  
    40.         public static Touch GetTouch(int index) {
    41. #if UNITY_EDITOR
    42.             Assert.IsTrue(fakeTouch.HasValue && index == 0);
    43.             return fakeTouch.Value;
    44. #else
    45.             return UnityEngine.Input.GetTouch(index);
    46. #endif
    47.         }
    48.  
    49.         static Touch? fakeTouch => SimulateTouchWithMouse.Instance.FakeTouch;
    50.  
    51.         public static Touch[] touches {
    52.             get {
    53. #if UNITY_EDITOR
    54.                 return fakeTouch.HasValue ? new[] {fakeTouch.Value} : new Touch[0];
    55. #else
    56.                 return UnityEngine.Input.touches;
    57. #endif
    58.             }
    59.         }
    60.     }
    61.  
    62.     internal class SimulateTouchWithMouse {
    63.         static SimulateTouchWithMouse instance;
    64.         float lastUpdateTime;
    65.         Vector3 prevMousePos;
    66.         Touch? fakeTouch;
    67.  
    68.  
    69.         public static SimulateTouchWithMouse Instance {
    70.             get {
    71.                 if (instance == null) {
    72.                     instance = new SimulateTouchWithMouse();
    73.                 }
    74.  
    75.                 return instance;
    76.             }
    77.         }
    78.  
    79.         public Touch? FakeTouch {
    80.             get {
    81.                 update();
    82.                 return fakeTouch;
    83.             }
    84.         }
    85.  
    86.         void update() {
    87.             if (Time.time != lastUpdateTime) {
    88.                 lastUpdateTime = Time.time;
    89.            
    90.                 var curMousePos = UnityEngine.Input.mousePosition;
    91.                 var delta = curMousePos - prevMousePos;
    92.                 prevMousePos = curMousePos;
    93.  
    94.                 fakeTouch = createTouch(getPhase(), delta);
    95.             }
    96.         }
    97.  
    98.         static TouchPhase? getPhase() {
    99.             if (UnityEngine.Input.GetMouseButtonDown(0)) {
    100.                 return TouchPhase.Began;
    101.             } else if (UnityEngine.Input.GetMouseButton(0)) {
    102.                 return TouchPhase.Moved;
    103.             } else if (UnityEngine.Input.GetMouseButtonUp(0)) {
    104.                 return TouchPhase.Ended;
    105.             } else {
    106.                 return null;
    107.             }
    108.         }
    109.  
    110.         static Touch? createTouch(TouchPhase? phase, Vector3 delta) {
    111.             if (!phase.HasValue) {
    112.                 return null;
    113.             }
    114.        
    115.             var curMousePos = UnityEngine.Input.mousePosition;
    116.             return new Touch {
    117.                 phase = phase.Value,
    118.                 type = TouchType.Indirect,
    119.                 position = curMousePos,
    120.                 rawPosition = curMousePos,
    121.                 fingerId = 0,
    122.                 tapCount = 1,
    123.                 deltaTime = Time.deltaTime,
    124.                 deltaPosition = delta
    125.             };
    126.         }
    127.     }
    128. }
    129.  
     

    Attached Files: