Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

3d space mmo click to move

Discussion in 'Scripting' started by pheekle, Aug 10, 2013.

  1. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    I'm trying to get a basic click to move script to work, but the click to move has to work in 3D space. Another feature I would like it to have is when clicked in open space, it keeps going forward, unless direction changed or you select and object to orbit around. Also I'm trying to make it so when you click to a new destination while moving it will make a turn slowly, like banking a semi truck around a corner.

    Not sure if there is a script out there like this.

    here is an example I put up.

    http://cerberium.com/test/Test.html

    The code I'm using!

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class moveOnMouseClick : MonoBehaviour {
    5.     private Transform myTransform;              // this transform
    6.     private Vector3 destinationPosition;        // The destination Point
    7.     private float destinationDistance;          // The distance between myTransform and destinationPosition
    8.  
    9.     public float moveSpeed;                     // The Speed the character will move
    10.  
    11.  
    12.  
    13.     void Start () {
    14.         myTransform = transform;                            // sets myTransform to this GameObject.transform
    15.         destinationPosition = myTransform.position;         // prevents myTransform reset
    16.     }
    17.  
    18.     void Update () {
    19.  
    20.         // keep track of the distance between this gameObject and destinationPosition
    21.         destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
    22.  
    23.         if(destinationDistance < .5f){      // To prevent shakin behavior when near destination
    24.             moveSpeed = 0;
    25.         }
    26.         else if(destinationDistance > .5f){         // To Reset Speed to default
    27.             moveSpeed = 3;
    28.         }
    29.  
    30.  
    31.         // Moves the Player if the Left Mouse Button was clicked
    32.         if (Input.GetMouseButtonDown(0) GUIUtility.hotControl ==0) {
    33.  
    34.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    35.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    36.             float hitdist = 0.0f;
    37.  
    38.             if (playerPlane.Raycast(ray, out hitdist)) {
    39.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    40.                 destinationPosition = ray.GetPoint(hitdist);
    41.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    42.                 myTransform.rotation = targetRotation;
    43.             }
    44.         }
    45.  
    46.         // Moves the player if the mouse button is hold down
    47.         else if (Input.GetMouseButton(0) GUIUtility.hotControl ==0) {
    48.  
    49.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    50.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    51.             float hitdist = 0.0f;
    52.  
    53.             if (playerPlane.Raycast(ray, out hitdist)) {
    54.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    55.                 destinationPosition = ray.GetPoint(hitdist);
    56.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    57.                 myTransform.rotation = targetRotation;
    58.             }
    59.         //  myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    60.         }
    61.  
    62.         // To prevent code from running if not needed
    63.         if(destinationDistance > .5f){
    64.             myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    65.         }
    66.     }
    67. }
    68. }
     
    Last edited: Aug 10, 2013
  2. xniinja

    xniinja

    Joined:
    Mar 12, 2011
    Posts:
    230
    Could you possibly post the script so we can see what's going on? Maybe we could change it up for you so it works in your situation.
     
  3. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    Whoops sorry! Edited OP.
     
  4. xniinja

    xniinja

    Joined:
    Mar 12, 2011
    Posts:
    230
    Hmm, nothing is popping out at me. However, how is this:

    Code (csharp):
    1.  
    2. if (Input.GetMouseButtonDown(0) GUIUtility.hotControl ==0) {
    3.  
    4.  
    5.  
    6.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    7.  
    8.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    9.  
    10.             float hitdist = 0.0f;
    11.  
    12.  
    13.  
    14.             if (playerPlane.Raycast(ray, out hitdist)) {
    15.  
    16.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    17.  
    18.                 destinationPosition = ray.GetPoint(hitdist);
    19.  
    20.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    21.  
    22.                 myTransform.rotation = targetRotation;
    23.  
    24.             }
    25.  
    26.         }
    27.  
    Different from this?

    Code (csharp):
    1.  
    2.  
    3.         // Moves the player if the mouse button is hold down
    4.  
    5.         else if (Input.GetMouseButton(0) GUIUtility.hotControl ==0) {
    6.  
    7.  
    8.  
    9.             Plane playerPlane = new Plane(Vector3.up, myTransform.position);
    10.  
    11.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    12.  
    13.             float hitdist = 0.0f;
    14.  
    15.  
    16.  
    17.             if (playerPlane.Raycast(ray, out hitdist)) {
    18.  
    19.                 Vector3 targetPoint = ray.GetPoint(hitdist);
    20.  
    21.                 destinationPosition = ray.GetPoint(hitdist);
    22.  
    23.                 Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
    24.  
    25.                 myTransform.rotation = targetRotation;
    26.  
    27.             }
    28.  
    29.         //  myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
    30.  
    31.         }
    32.  
    It seems as though you could take the else out to try simplifying the code. As for the moving on the X-Axis, are you sure your plane is pointing in the right direction? I know it seems as though it is, but everything else looks fine so that's the only thing that's sticking out at me.
     
  5. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    I'm actually not using a plane at the moment, do you think that may be my problem? I just using open space. If your curious how it looks on my side, heres a picture. http://prntscr.com/1kgjdt
     
  6. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    Ok, I edited the post with an example, and updated code. I also tried to make my explanation clearer. I'm also new to coding,so if you don't mind giving me an explanation what was changed or added would be great thanks!
     
    Last edited: Aug 10, 2013
  7. Uncasid

    Uncasid

    Joined:
    Oct 5, 2012
    Posts:
    193
    yeah, you have to use a plane to intersect, else you are clicking at infinity. are you getting a hit from the raycast on your mouse to world space? also, just as a suggestion, build a mouse manager class that does events. like a click is a press down + release. it will make your logic more easy to read and modify.
     
  8. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    Is there a way of making a boxed like plane? So that where I click within the box it moves too? Any suggestions on how to make this work?
     
  9. Uncasid

    Uncasid

    Joined:
    Oct 5, 2012
    Posts:
    193
    You have the right idea set up for the base of it. I am going to hook you up and get you started. This is the mouse manager + code you are trying to build, that I have developed:

    Yes, it will have some bugs right now, as I removed some stuff you don't need to see. This is not the best implementation, as it doesn't follow true OO standards. The class should only do mouse stuff, and trigger events (which I have already started to implement with selection changes). Finish implementing the event stuff, then make an object selection / interaction manager that uses the events from the mouse. My hope is that this class won't make you lazy; learn how I did things, grow, don't just take and use.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. public class MouseHandler : MonoBehaviour
    7. {
    8.  
    9.     #region Event Handling
    10.  
    11.     /// <summary>
    12.     /// This event fires when a user selects something different
    13.     /// </summary>
    14.     public event System.Action OnSelectedObjectsChanged;
    15.  
    16.     /// <summary>
    17.     /// This event fires when the user changes the object grouping
    18.     /// </summary>
    19.     public event System.Action OnGroupedObjectsChanged;
    20.  
    21.     #endregion
    22.  
    23.     #region Mouse Section
    24.  
    25.     #region Private classes for data handling
    26.     class DragParams {
    27.         public Vector3 StartPosition;
    28.         public Vector3 EndPosition;
    29.        
    30.         public DragParams (Vector3 strt, Vector3 end) {
    31.             StartPosition = strt;
    32.             EndPosition = end;
    33.         }
    34.     }
    35.    
    36.     #endregion
    37.    
    38.     /// <summary>
    39.     /// Set to true if left mouse button is down
    40.     /// </summary>
    41.     public bool LeftDown = false;
    42.    
    43.     /// <summary>
    44.     /// Set to true if the left mouse button is up
    45.     /// </summary>
    46.     public bool LeftUp = true;
    47.    
    48.     /// <summary>
    49.     /// Set to true if the user presses down, then releases the mouse
    50.     /// </summary>
    51.     public bool LeftClick = false;
    52.    
    53.     /// <summary>
    54.     /// Set to true if the user clicks twice between the allowed double click time with the left mouse button
    55.     /// </summary>
    56.     public bool LeftDoubleClick = false;
    57.    
    58.     /// <summary>
    59.     /// Set to true if the Right mouse button is down
    60.     /// </summary>
    61.     public bool RightDown = false;
    62.    
    63.     /// <summary>
    64.     /// Set to true if the right mouse button is up
    65.     /// </summary>
    66.     public bool RightUp = true;
    67.    
    68.     /// <summary>
    69.     /// Set to true if the user presses down, then releases the mouse
    70.     /// </summary>
    71.     public bool RightClick = false;
    72.    
    73.     /// <summary>
    74.     /// Set to true if the user clicks twice between the allowed double click time with the right mouse button
    75.     /// </summary>
    76.     public bool RightDoubleClick = false;
    77.    
    78.     /// <summary>
    79.     /// The double click time for checking
    80.     /// </summary>
    81.     public int DoubleClickTime = 600;
    82.    
    83.     /// <summary>
    84.     /// Change of x based on the last update.  returns a negative value if the user moved left, possitive if moved right
    85.     /// </summary>
    86.     public float MouseChangeX = 0f;
    87.    
    88.     /// <summary>
    89.     /// Change of y based on the last update.  returns a negative value if the user moved up, possitive if moved down
    90.     /// </summary>
    91.     public float MouseChangeY = 0f;
    92.    
    93.     /// <summary>
    94.     /// The click select depth, how deep a bounding box checks for intersects
    95.     /// </summary>
    96.     public float ClickSelectDepth = 10f;
    97.    
    98.     /// <summary>
    99.     /// The default color of the selection box.
    100.     /// </summary>
    101.     public Color SelectionBoxDefaultColor = new Color(41, 93, 101, 255);
    102.    
    103.     /// <summary>
    104.     /// The attack color of the selection box attack.
    105.     /// </summary>
    106.     public Color SelectionBoxAttackColor = new Color(200, 27, 27, 255);
    107.    
    108.     /// <summary>
    109.     /// The color of the selected object.
    110.     /// </summary>
    111.     public Color SelectedObjectColor = Color.white;
    112.    
    113.     /// <summary>
    114.     /// The selection signifier offset.
    115.     /// </summary>
    116.     public Vector3 SelectionSignifierOffset = new Vector3(0, 0, -0.1f);
    117.    
    118.     /// <summary>
    119.     /// Layers to check clicks on
    120.     /// </summary>
    121.     public LayerMask ClickCheckLayers;
    122.    
    123.     private float StartX = 0;
    124.     private float StartY = 0;
    125.     private float PreviousX = 0;
    126.     private float PreviousY = 0;
    127.     private System.DateTime firstClick;
    128.     private System.DateTime secondClick;
    129.     private int ClickCount = 0;
    130.     private GameObject _movementPlate;
    131.     private GameObject spam;
    132.    
    133.     #endregion
    134.    
    135.     #region Selection Section
    136.    
    137.     /// <summary>
    138.     /// Selected object properties struct, used to track selected objects
    139.     /// </summary>
    140.     public class SelectedObjectProperties {
    141.         public GameObject gameObject;
    142.        
    143.         public SelectedObjectProperties(GameObject pgameObject) {
    144.             gameObject = pgameObject;
    145.         }
    146.        
    147.     }
    148.    
    149.     /// <summary>
    150.     /// These are objects selected by the mouse, currently
    151.     /// </summary>
    152.     public List<SelectedObjectProperties> SelectedObjects;
    153.    
    154.     /// <summary>
    155.     /// These are game objects assigned to a group
    156.     /// </summary>
    157.     public Dictionary<KeyCode, List<SelectedObjectProperties>> SavedSelectedObjects;
    158.    
    159.     RaycastHit hitTesting;
    160.    
    161.     /// <summary>
    162.     /// The selector box for click drag stuff
    163.     /// </summary>
    164.     public GameObject selectorBox;
    165.    
    166.     /// <summary>
    167.     /// The movement plate.
    168.     /// </summary>
    169.     public GameObject MovementPlate;
    170.    
    171.     /// <summary>
    172.     /// The position indicator of where a user click / selects an object to go
    173.     /// </summary>
    174.     public GameObject PositionIndicator;
    175.  
    176.     #endregion
    177.  
    178.     void Start() {
    179.        
    180.         // Get the scene spam object
    181.         spam = GameObject.Find("SceneSpam");
    182.  
    183.         SelectedObjects = new List<SelectedObjectProperties>();
    184.         SavedSelectedObjects = new Dictionary<KeyCode, List<SelectedObjectProperties>>();
    185.        
    186.         hitTesting = new RaycastHit();
    187.        
    188.         // Create the movement plate
    189.         _movementPlate = (GameObject)Instantiate(MovementPlate, Vector3.zero, Quaternion.identity);
    190.         _movementPlate.SetActive(false);
    191.        
    192.     }
    193.    
    194.     /// <summary>
    195.     /// Update all mouse state information
    196.     /// </summary>
    197.     void LateUpdate()
    198.     {
    199.         // reset status
    200.         LeftClick = false;
    201.         RightClick = false;
    202.         LeftDoubleClick = false;
    203.         RightDoubleClick = false;
    204.  
    205.         #region Test left mouse button
    206.  
    207.         if (Input.GetMouseButton(0))
    208.         {
    209.             if (!LeftDown)
    210.             {
    211.                 StartX = Input.mousePosition.x;
    212.                 StartY = Input.mousePosition.y;
    213.             }
    214.  
    215.             LeftDown = true;
    216.         }
    217.         else
    218.         {
    219.  
    220.             // If LeftClick = true and LeftDown = true  MB1 = false
    221.             // and double click time in range, we have a double click
    222.             if (ClickCount == 2)
    223.             {
    224.                 // Make sure it is in the range
    225.                 if (secondClick.Subtract(firstClick).TotalMilliseconds <= DoubleClickTime)
    226.                 {
    227.                     // double click took place
    228.                     LeftDoubleClick = true;
    229.                     ClickCount = 0;
    230.                 }
    231.                 else
    232.                 {
    233.                     // Reset the clicks if the user clicked 2 times
    234.                     ClickCount = 0;
    235.                 }
    236.             }
    237.  
    238.             // If LeftDown is true and current MB1 is not, we have a click
    239.             if (LeftDown)
    240.             {
    241.                 ClickCount++;
    242.                 LeftClick = true;
    243.  
    244.                 // Set the start click time for checking double clicks
    245.                 if (ClickCount == 1)
    246.                     firstClick = System.DateTime.Now;
    247.                 else
    248.                     secondClick = System.DateTime.Now;
    249.  
    250.             }
    251.  
    252.             // LeftDown is no longer true
    253.             LeftDown = false;
    254.             LeftUp = true;
    255.         }
    256.         #endregion
    257.  
    258.         #region Test right button
    259.  
    260.         if (Input.GetMouseButton(1))
    261.         {
    262.             if (!RightDown)
    263.             {
    264.                 StartX = Input.mousePosition.x;
    265.                 StartY = Input.mousePosition.y;
    266.             }
    267.  
    268.             RightDown = true;
    269.  
    270.         }
    271.         else
    272.         {
    273.             RightDoubleClick = false;
    274.  
    275.             // If LeftClick = true and LeftDown = true  MB1 = false
    276.             // and double click time in range, we have a double click
    277.             if (RightClick  RightDown)
    278.             {
    279.                 // Make sure it is in the range
    280.                 if (System.DateTime.Now.Subtract(firstClick).TotalMilliseconds <= DoubleClickTime)
    281.                 {
    282.                     // double click took place
    283.                     RightDoubleClick = true;
    284.                 }
    285.             }
    286.  
    287.             // If LeftDown is true and current MB1 is not, we have a click
    288.             if (RightDown)
    289.             {
    290.                 RightClick = true;
    291.  
    292.                 // Set the start click time for checking double clicks
    293.                 firstClick = System.DateTime.Now;
    294.             }
    295.  
    296.             // LeftDown is no longer true
    297.             RightDown = false;
    298.             RightUp = true;
    299.         }
    300.         #endregion
    301.  
    302.         #region Check the change in x / y
    303.  
    304.         MouseChangeX = PreviousX - Input.mousePosition.x;
    305.         MouseChangeY = PreviousY - Input.mousePosition.y;
    306.  
    307.         #endregion
    308.  
    309.         PreviousX = Input.mousePosition.x;
    310.         PreviousY = Input.mousePosition.y;
    311.        
    312.         // Process events here
    313.         // Left Click
    314.         if (LeftClick) on_LeftClick(new Vector3(StartX, StartY));
    315.         // Left Double Click
    316.         if (LeftDoubleClick) on_LeftDoubleClick(new Vector3(StartX, StartY));
    317.         // Left Click Dragging
    318.         if (LeftDown  (Mathf.Abs(MouseChangeX) > 0 || Mathf.Abs(MouseChangeY) > 0)) on_LeftClickDragging(new DragParams(new Vector3(StartX, StartY), new Vector3(Input.mousePosition.x, Input.mousePosition.y)));
    319.         // Left Click Drag
    320.         if (LeftClick  ((StartX != PreviousX) || (StartY != PreviousY))) on_LeftDrag(new DragParams(new Vector3(StartX, StartY), new Vector3(Input.mousePosition.x, Input.mousePosition.y)));
    321.         // Right Click
    322.         if (RightClick) on_RightClick(new Vector3(StartX, StartY));
    323.         // Right Double Click
    324.         if (RightDoubleClick) on_RightDoubleClick(new Vector3(StartX, StartY));
    325.         // Right Click Dragging
    326.         if (RightDown  (Mathf.Abs(MouseChangeX) > 0 || Mathf.Abs(MouseChangeY) > 0)) on_RightClickDragging(new DragParams(new Vector3(StartX, StartY), new Vector3(Input.mousePosition.x, Input.mousePosition.y)));
    327.         // Right Click Drag
    328.         if (RightClick  ((StartX != PreviousX) || (StartY != PreviousY))) on_RightDrag(new DragParams(new Vector3(StartX, StartY), new Vector3(Input.mousePosition.x, Input.mousePosition.y)));
    329.        
    330.         // Process Key Command here
    331.         // Put Saved
    332.         if ((Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))  (Input.GetKeyUp(KeyCode.Alpha1) || Input.GetKeyUp(KeyCode.Alpha2) || Input.GetKeyUp(KeyCode.Alpha3) || Input.GetKeyUp(KeyCode.Alpha4) || Input.GetKeyUp(KeyCode.Alpha5) || Input.GetKeyUp(KeyCode.Alpha6) || Input.GetKeyUp(KeyCode.Alpha7) || Input.GetKeyUp(KeyCode.Alpha8) || Input.GetKeyUp(KeyCode.Alpha9) || Input.GetKeyUp(KeyCode.Alpha0))) { on_SaveSelections(); }
    333.        
    334.         // Recall Saved
    335.         if ((!Input.GetKey(KeyCode.LeftAlt)  !Input.GetKey(KeyCode.RightAlt))  (Input.GetKeyUp(KeyCode.Alpha1) || Input.GetKeyUp(KeyCode.Alpha2) || Input.GetKeyUp(KeyCode.Alpha3) || Input.GetKeyUp(KeyCode.Alpha4) || Input.GetKeyUp(KeyCode.Alpha5) || Input.GetKeyUp(KeyCode.Alpha6) || Input.GetKeyUp(KeyCode.Alpha7) || Input.GetKeyUp(KeyCode.Alpha8) || Input.GetKeyUp(KeyCode.Alpha9) || Input.GetKeyUp(KeyCode.Alpha0))) { on_RecallSelections(); }
    336.        
    337.         #region Do the following if there are selected objects
    338.        
    339.         // Position the movement plate if an object is selected
    340.         if (SelectedObjects.Count > 0) {
    341.            
    342.             Vector3 sums = new Vector3(0, 0, 0);
    343.            
    344.             SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    345.                 // Sum the x / y / z
    346.                 sums += obj.gameObject.transform.localPosition;
    347.                
    348.                 Vector3 bounds = obj.gameObject.renderer.bounds.size;
    349.                
    350.                 // Need to find the largest bound
    351.                 float largest = (bounds.x > bounds.y ? bounds.x : bounds.y);
    352.                 largest = (largest > bounds.z ? largest : bounds.z);
    353.                 // ---END create the section line
    354.                
    355.             });
    356.            
    357.             _movementPlate.transform.position = (sums / SelectedObjects.Count);
    358.         }
    359.        
    360.         #endregion
    361.        
    362.         // Final step is to draw the selectors
    363.         #region Draw the click drag selector
    364.        
    365.         // Draw click drag
    366.         if ((LeftDown || (RightDown  (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))))  (Mathf.Abs(MouseChangeX) > 2 || Mathf.Abs(MouseChangeY) > 2)) {
    367.            
    368.             // set the color of the click drag
    369.             if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
    370.                 selectorBox.GetComponent<UISlicedSprite>().color = SelectionBoxAttackColor;
    371.             } else {
    372.                 selectorBox.GetComponent<UISlicedSprite>().color = SelectionBoxDefaultColor;
    373.             }
    374.            
    375.             // Set to mouse position
    376.             float xPosition = StartX - (Screen.width / 2f);
    377.             float yPosition = StartY - (Screen.height / 2f);
    378.             float xPositionR = Input.mousePosition.x - (Screen.width / 2f);
    379.             float yPositionR = Input.mousePosition.y - (Screen.height / 2f);
    380.            
    381.             /* Quadrants
    382.                    1  |  2
    383.                 -------------    
    384.                    3  |  4
    385.             */
    386.            
    387.             // Check quadrant 4 first
    388.             if ((xPositionR - xPosition) >=0  (yPosition - yPositionR) >= 0) {
    389.                 selectorBox.transform.localPosition = new Vector3(xPosition, yPosition, 62);
    390.                 selectorBox.transform.localScale = new Vector3(xPositionR - xPosition, yPosition - yPositionR, 0);
    391.             }
    392.             // Quadrant 3
    393.             else if ((xPositionR - xPosition) < 0  (yPosition - yPositionR) >= 0) {
    394.                 // origin X follows mouse, width / height = mouse first click position
    395.                 selectorBox.transform.localPosition = new Vector3(xPositionR, yPosition, 62);
    396.                 selectorBox.transform.localScale = new Vector3(xPosition - xPositionR, yPosition - yPositionR, 0);
    397.             }
    398.             // Quadrant 2
    399.             else if ((xPositionR - xPosition) >= 0  (yPosition - yPositionR) < 0) {
    400.                 // origin X follows mouse, width / height = mouse first click position
    401.                 selectorBox.transform.localPosition = new Vector3(xPosition, yPositionR, 62);
    402.                 selectorBox.transform.localScale = new Vector3(xPositionR - xPosition, yPositionR - yPosition, 0);
    403.             }
    404.             // Quadrant 1
    405.             else if ((xPositionR - xPosition) < 0  (yPosition - yPositionR) < 0) {
    406.                 // origin follows mouse, width / height = mouse first click position
    407.                 selectorBox.transform.localPosition = new Vector3(xPositionR, yPositionR, 62);
    408.                 selectorBox.transform.localScale = new Vector3(xPosition - xPositionR, yPositionR - yPosition, 0);
    409.             }          
    410.  
    411.         }
    412.        
    413.         #endregion
    414.        
    415.     }
    416.  
    417.     #region Helper Methods
    418.  
    419.     public void SelectOneObject(GameObject go)
    420.     {
    421.  
    422.         // Clear the selected list
    423.         RemoveSelected();
    424.  
    425.         // add it to the list
    426.         SelectedObjects.Add(new SelectedObjectProperties(go.transform.gameObject));
    427.  
    428.         // make the circle selection around it
    429.        
    430.         // Draw movement plate
    431.         _movementPlate.SetActive(true);
    432.  
    433.     }
    434.  
    435.     public void RemoveSelected()
    436.     {
    437.         // clear the selection list
    438.         SelectedObjects.Clear();
    439.     }
    440.  
    441.     #endregion
    442.  
    443.     #region Handle left click events
    444.    
    445.     // Note to you, move this all to events.  I was just prototyping.
    446.    
    447.     /// <summary>
    448.     /// Lefts the click.
    449.     /// </summary>
    450.     /// <param name='mousePosition'>
    451.     /// Mouse position.
    452.     /// </param>
    453.     void on_LeftClick(Vector3 mousePosition) {
    454.  
    455.         bool FireEvent = false;
    456.  
    457.         // Check if shift is being pressed, if not, clear all objects
    458.         if (!Input.GetKey(KeyCode.LeftShift)  !Input.GetKey(KeyCode.RightShift)) {
    459.  
    460.             if (SelectedObjects.Count > 0) { FireEvent = true; }
    461.  
    462.             RemoveSelected();
    463.  
    464.         }
    465.        
    466.         // Cast a ray to check for a new selection
    467.         if (Physics.Raycast(Camera.main.ScreenPointToRay(mousePosition), out hitTesting, 1000f, ClickCheckLayers.value))
    468.         {
    469.             // We have a hit!! add it to the list
    470.             if (hitTesting.transform.gameObject.layer == 8) {
    471.                 SelectedObjects.Add( new SelectedObjectProperties(hitTesting.transform.gameObject) );
    472.                 _movementPlate.SetActive(true);
    473.                
    474.                 FireEvent = true;
    475.  
    476.             } else {
    477.                 // Disable the movement plate
    478.                 _movementPlate.SetActive(false);
    479.             }
    480.         } else {
    481.             // Disable the movement plate
    482.             _movementPlate.SetActive(false);
    483.         }
    484.  
    485.         if (FireEvent  OnSelectedObjectsChanged != null) { OnSelectedObjectsChanged(); }
    486.  
    487.     }
    488.    
    489.     /// <summary>
    490.     /// On_s the left double click.
    491.     /// </summary>
    492.     /// <param name='mousePosition'>
    493.     /// Mouse position.
    494.     /// </param>
    495.     void on_LeftDoubleClick(Vector3 mousePosition) {
    496.        
    497.         // make sure we have a ship selected already
    498.         if (SelectedObjects.Count > 0) {
    499.        
    500.             // Select all objects of the same type
    501.             foreach (Collider co in RadarHandler.GetCollisions) {
    502.                
    503.                 throw new exception ("Do the selection thing here that happens when you double click");
    504.                
    505.                 if (true) {
    506.                    
    507.                     SelectedObjects.Add(new SelectedObjectProperties(co.gameObject));
    508.                    
    509.                 }
    510.                
    511.             }
    512.  
    513.             if (OnSelectedObjectsChanged != null) { OnSelectedObjectsChanged(); }
    514.  
    515.         }
    516.     }
    517.    
    518.     /// <summary>
    519.     /// On_s the left click dragging.
    520.     /// </summary>
    521.     void on_LeftClickDragging(DragParams param) {
    522.     }
    523.    
    524.     /// <summary>
    525.     /// On_the left drag.
    526.     /// </summary>
    527.     void on_LeftDrag(DragParams param) {
    528.        
    529.         float posX = selectorBox.transform.localPosition.x + (Screen.width / 2f);
    530.        
    531.         // this is one the wrong side of the screen, does the oposite
    532.         float posY = ((Screen.height / 2f) - selectorBox.transform.localPosition.y) + (selectorBox.transform.localScale.y);
    533.  
    534.         GameObject[] fndObjects = GetObjectsInLayerMask(FriendlyLayers);//8);
    535.        
    536.         if (fndObjects != null  fndObjects.Length > 0) {
    537.            
    538.             // Create a screen rect
    539.             Rect rec = new Rect(posX, Screen.height - posY, selectorBox.transform.localScale.x, selectorBox.transform.localScale.y);
    540.            
    541.             // Check if the objects are in the screen rect
    542.             // There is probably a better implementation of this
    543.             foreach (GameObject go in fndObjects) {
    544.                
    545.                 if ( rec.Contains(Camera.main.WorldToScreenPoint(go.transform.localPosition)) ) {
    546.                
    547.                     SelectedObjects.Add( new SelectedObjectProperties(go) );
    548.                    
    549.                 }
    550.             }
    551.            
    552.             if (OnSelectedObjectsChanged != null) { OnSelectedObjectsChanged(); }
    553.  
    554.         }
    555.        
    556.         if (SelectedObjects.Count > 0) {
    557.             _movementPlate.SetActive(true);
    558.         }
    559.        
    560.         // Reset the selection box
    561.         selectorBox.transform.localPosition = new Vector3(-10000, 0, 62);
    562.         selectorBox.transform.localScale = new Vector3(10, 10, 0);
    563.     }
    564.    
    565.    
    566.     #endregion
    567.    
    568.     #region Handle right click events
    569.    
    570.     /// <summary>
    571.     /// On_s the right click.
    572.     /// </summary>
    573.     /// <param name='mousePosition'>
    574.     /// Mouse position.
    575.     /// </param>
    576.     void on_RightClick(Vector3 mousePosition) {
    577.        
    578.         // Attack targets
    579.         if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) {
    580.         } else {
    581.        
    582.             // If dragging ignore all of this
    583.             if (((StartX == PreviousX)  (StartY == PreviousY))) {
    584.                
    585.                 // Tells units to move / attack / follow depending on what they clicked... so raycast time!
    586.                 // Cast a ray to check for a new selection
    587.                 if (Physics.Raycast(Camera.main.ScreenPointToRay(mousePosition), out hitTesting))
    588.                 {
    589.                    
    590.                     // We have a hit!! Detect if friendly or foe.. if foe, send to attack, if friendly, follow
    591.                     if (hitTesting.transform.gameObject.layer == ENEMY_LAYER_BRO) {
    592.                        
    593.                         // Object is enemy, instruct selected objects to attack it
    594.                         SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    595.                             // Make sure they are ShipFSM Objects, other objects aren't treated the same
    596.                             if (obj.gameObject.GetComponent<ShipFSM>() != null) {
    597.                                
    598.                                 // Clear the line params and add the new line
    599.                                 //lineParams.Clear();
    600.                                 obj.gameObject.GetComponent<ShipFSM>().AttackTarget(hitTesting.transform.gameObject);
    601.                             }
    602.                         });
    603.                     } else if (hitTesting.transform.gameObject.layer == FRIENDLY_LAYER_BRO) {
    604.                         // Friendly!!  If object is selected, instruct it to follow
    605.                        
    606.                         // Do this if objects are selected
    607.                         if (SelectedObjects.Count > 0) {
    608.                             // Instruct to follow
    609.                         }
    610.                        
    611.                     }
    612.                 } else {
    613.                     // Nothing hit, send to point based on x/y plane
    614.                    
    615.                     if (SelectedObjects.Count > 0) {
    616.                        
    617.                         // NOTE - this system will change
    618.                         // it will collect object positions based on location of a calculated center point
    619.                         // it will then use a look vector to decide direction when placing
    620.                         // usually from previous position to new position
    621.                         // that way, objects move to the same point that they were at in relation to other ships around them
    622.                        
    623.                         // Get the average of all Y positions
    624.                         float y = 0f;
    625.                        
    626.                         // Sum the Y's of all selected game objects
    627.                         SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    628.                             y += obj.gameObject.transform.localPosition.y;
    629.                         });
    630.        
    631.                         Ray worldRay = Camera.main.ScreenPointToRay(mousePosition);
    632.                         float enter;
    633.                        
    634.                         // Selectt the Y average center of the selected objects
    635.                         Plane xz = new Plane(Vector3.up, new Vector3(0f, y / SelectedObjects.Count, 0f));
    636.                        
    637.                         xz.Raycast(worldRay, out enter);
    638.                         Vector3 intersectPoint = worldRay.GetPoint(enter);
    639.        
    640.                         // Instruct the gameobject to move (if the have the class), and keeps their Y value
    641.                         SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    642.                             // Make sure they are ShipFSM Objects, other objects aren't treated the same
    643.                             if (obj.gameObject.GetComponent<ShipFSM>() != null) {
    644.                                
    645.                                 obj.gameObject.GetComponent<ShipFSM>().MoveToLocation(intersectPoint + new Vector3(0, obj.gameObject.transform.position.normalized.y, 0));
    646.                                
    647.                                 // Draw the location point clicked
    648.                                 if (PositionIndicator != null) {
    649.                                     GameObject PositionIndicatortmp = (GameObject)Instantiate(PositionIndicator,intersectPoint /*+ new Vector3(0, obj.gameObject.transform.position.y, 0)*/, Quaternion.identity);
    650.                                     GameObject.Destroy(PositionIndicatortmp, 3);
    651.                                 }
    652.                                
    653.                             }
    654.                         });                            
    655.                        
    656.                     }
    657.                 }
    658.             }
    659.         }
    660.     }
    661.    
    662.     /// <summary>
    663.     /// On_s the right double click.
    664.     /// </summary>
    665.     /// <param name='mousePosition'>
    666.     /// Mouse position.
    667.     /// </param>
    668.     void on_RightDoubleClick(Vector3 mousePosition) {
    669.        
    670.     }
    671.    
    672.     /// <summary>
    673.     /// On_s the left click dragging.
    674.     /// </summary>
    675.     void on_RightClickDragging(DragParams param) {
    676.        
    677.         // Do a red box select drag for attacking
    678.         if (!Input.GetKey(KeyCode.LeftControl)  !Input.GetKey(KeyCode.RightControl)) {
    679.             // Draw a line if an object is selected
    680.             if (SelectedObjects.Count > 0) {
    681.    
    682.                 // Intersect test on objects XZ needs to be done each time, because the object may already be moving
    683.                 // NOTE: in the future, where ships placements are in relation to the center X / Y will be their
    684.                 //       destination point..  this is a "formation" like approach.. though
    685.                 //       we may actually implement a method to set formations
    686.                
    687.                 #region Handle XZ
    688.                
    689.                 // Get the average of all Y positions
    690.                 float y = 0f;
    691.                
    692.                 // Sum the y's of all objects to get the average Y
    693.                 SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    694.                     y += obj.gameObject.transform.localPosition.y;
    695.                 });
    696.                
    697.                 // Create the ray that will come from the mouse
    698.                 Ray worldRay = Camera.main.ScreenPointToRay(param.StartPosition);
    699.                 float enter;
    700.                
    701.                 // Create the XZ plane to test mouse intersects using the average Y as the point.  For one object it will
    702.                 // be the objects Y center.. Y=0 in it's local space
    703.                 Plane xz = new Plane(Vector3.up, new Vector3(0f, y / SelectedObjects.Count, 0f));
    704.                
    705.                 xz.Raycast(worldRay, out enter);
    706.                 Vector3 intersectPointXZ = worldRay.GetPoint(enter);
    707.                
    708.                 #endregion
    709.    
    710.                 #region Handle YX
    711.                
    712.                 // Clamp the mouse X
    713.                 //Vector3 clampedEnd = new Vector3(param.StartPosition.x, param.EndPosition.y, 0f);
    714.                
    715.                 // Create the ray that will come from the mouse
    716.                 worldRay = Camera.main.ScreenPointToRay(/*clampedEnd);//*/param.EndPosition);
    717.                
    718.                 // Create the XZ plane to test mouse intersects using the average Y as the point.  For one object it will
    719.                 // be the objects Y center.. Y=0 in it's local space
    720.                 Plane yx = new Plane(Vector3.left, new Vector3(intersectPointXZ.x, 0f, 0f));
    721.                
    722.                 yx.Raycast(worldRay, out enter);
    723.                 Vector3 intersectPointYX = worldRay.GetPoint(enter);
    724.                
    725.                 #endregion
    726.                
    727.             }
    728.         }
    729.     }
    730.    
    731.     /// <summary>
    732.     /// On_the left drag.
    733.     /// </summary>
    734.     void on_RightDrag(DragParams param) {
    735.         // Draw a line if an object is selected
    736.         if (SelectedObjects.Count > 0) {
    737.            
    738.             // Intersect test on objects XZ needs to be done each time, because the object may already be moving
    739.             // NOTE: in the future, where ships placements are in relation to the center X / Y will be their
    740.             //       destination point..  this is a "formation" like approach.. though
    741.             //       we may actually implement a method to set formations
    742.            
    743.             #region Handle XZ
    744.             // Get the average of all Y positions
    745.             float y = 0f;
    746.            
    747.             // Sum the y's of all objects to get the average Y
    748.             SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    749.                 y += obj.gameObject.transform.localPosition.y;
    750.             });
    751.            
    752.             // Create the ray that will come from the mouse
    753.             Ray worldRay = Camera.main.ScreenPointToRay(param.StartPosition);
    754.             float enter;
    755.            
    756.             // Create the XZ plane to test mouse intersects using the average Y as the point.  For one object it will
    757.             // be the objects Y center.. Y=0 in it's local space
    758.             Plane xz = new Plane(Vector3.up, new Vector3(0f, y / SelectedObjects.Count, 0f));
    759.            
    760.             xz.Raycast(worldRay, out enter);
    761.             Vector3 intersectPointXZ = worldRay.GetPoint(enter);
    762.             #endregion
    763.  
    764.             #region Handle YX
    765.             // Create the ray that will come from the mouse
    766.             worldRay = Camera.main.ScreenPointToRay(param.EndPosition);
    767.            
    768.             // Create the XZ plane to test mouse intersects using the average Y as the point.  For one object it will
    769.             // be the objects Y center.. Y=0 in it's local space
    770.             Plane yx = new Plane(Vector3.left, new Vector3(intersectPointXZ.x, 0f, 0));
    771.            
    772.             yx.Raycast(worldRay, out enter);
    773.             Vector3 intersectPointYX = worldRay.GetPoint(enter);
    774.            
    775.             #endregion
    776.            
    777.             // Instruct objects to go to intersectPointYX
    778.             SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    779.                 obj.gameObject.GetComponent<ShipFSM>().MoveToLocation(intersectPointYX + new Vector3(0, obj.gameObject.transform.position.normalized.y, 0));
    780.                
    781.                 // Draw the location point clicked
    782.                 if (PositionIndicator != null) {
    783.                     GameObject PositionIndicatortmp = (GameObject)Instantiate(PositionIndicator, intersectPointYX, Quaternion.identity);
    784.                     GameObject.Destroy(PositionIndicatortmp, 3);
    785.                 }
    786.             });
    787.            
    788.         }
    789.        
    790.         // Reset the selection box
    791.         selectorBox.transform.localPosition = new Vector3(-10000, 0, 62);
    792.         selectorBox.transform.localScale = new Vector3(10, 10, 0);
    793.     }
    794.    
    795.     #endregion
    796.    
    797.     #region Handle keyboard input
    798.    
    799.     /// <summary>
    800.     /// Saves the currently selected objects
    801.     /// </summary>
    802.     void on_SaveSelections() {
    803.        
    804.         KeyCode keyPressed = KeyCode.Break;
    805.        
    806.         #region Save to which section?
    807.        
    808.         if (Input.GetKeyUp(KeyCode.Alpha1)) {
    809.             keyPressed = KeyCode.Alpha1;
    810.         } else if (Input.GetKeyUp(KeyCode.Alpha2)) {
    811.             keyPressed = KeyCode.Alpha2;
    812.         } else if (Input.GetKeyUp(KeyCode.Alpha3)) {
    813.             keyPressed = KeyCode.Alpha3;
    814.         } else if (Input.GetKeyUp(KeyCode.Alpha4)) {
    815.             keyPressed = KeyCode.Alpha4;
    816.         } else if (Input.GetKeyUp(KeyCode.Alpha5)) {
    817.             keyPressed = KeyCode.Alpha5;
    818.         } else if (Input.GetKeyUp(KeyCode.Alpha6)) {
    819.             keyPressed = KeyCode.Alpha6;
    820.         } else if (Input.GetKeyUp(KeyCode.Alpha7)) {
    821.             keyPressed = KeyCode.Alpha7;
    822.         } else if (Input.GetKeyUp(KeyCode.Alpha8)) {
    823.             keyPressed = KeyCode.Alpha8;
    824.         } else if (Input.GetKeyUp(KeyCode.Alpha9)) {
    825.             keyPressed = KeyCode.Alpha9;
    826.         } else if (Input.GetKeyUp(KeyCode.Alpha0)) {
    827.             keyPressed = KeyCode.Alpha0;
    828.         }
    829.        
    830.         #endregion
    831.        
    832.         if (keyPressed != KeyCode.Break) {
    833.             if (SavedSelectedObjects.ContainsKey(keyPressed)) {
    834.                 SavedSelectedObjects[keyPressed].Clear();
    835.                 SavedSelectedObjects[keyPressed].AddRange(SelectedObjects);
    836.  
    837.                 if (OnGroupedObjectsChanged != null) { OnGroupedObjectsChanged(); }
    838.  
    839.             } else {
    840.                 List<SelectedObjectProperties> newLst = new List<SelectedObjectProperties>();
    841.                 newLst.AddRange(SelectedObjects);
    842.                 SavedSelectedObjects.Add(keyPressed, newLst);
    843.  
    844.                 if (OnGroupedObjectsChanged != null) { OnGroupedObjectsChanged(); }
    845.  
    846.             }
    847.         }
    848.     }
    849.    
    850.     /// <summary>
    851.     /// Handle the on recall key press.. clears current selected, adds the new ones
    852.     /// </summary>
    853.     void on_RecallSelections() {
    854.        
    855.         KeyCode keyPressed = KeyCode.Break;
    856.        
    857.         #region Recall to which section?
    858.        
    859.         if (Input.GetKeyUp(KeyCode.Alpha1)) {
    860.             keyPressed = KeyCode.Alpha1;
    861.         } else if (Input.GetKeyUp(KeyCode.Alpha2)) {
    862.             keyPressed = KeyCode.Alpha2;
    863.         } else if (Input.GetKeyUp(KeyCode.Alpha3)) {
    864.             keyPressed = KeyCode.Alpha3;
    865.         } else if (Input.GetKeyUp(KeyCode.Alpha4)) {
    866.             keyPressed = KeyCode.Alpha4;
    867.         } else if (Input.GetKeyUp(KeyCode.Alpha5)) {
    868.             keyPressed = KeyCode.Alpha5;
    869.         } else if (Input.GetKeyUp(KeyCode.Alpha6)) {
    870.             keyPressed = KeyCode.Alpha6;
    871.         } else if (Input.GetKeyUp(KeyCode.Alpha7)) {
    872.             keyPressed = KeyCode.Alpha7;
    873.         } else if (Input.GetKeyUp(KeyCode.Alpha8)) {
    874.             keyPressed = KeyCode.Alpha8;
    875.         } else if (Input.GetKeyUp(KeyCode.Alpha9)) {
    876.             keyPressed = KeyCode.Alpha9;
    877.         } else if (Input.GetKeyUp(KeyCode.Alpha0)) {
    878.             keyPressed = KeyCode.Alpha0;
    879.         }
    880.        
    881.         #endregion
    882.        
    883.         if (keyPressed != KeyCode.Break) {
    884.             if (SavedSelectedObjects.ContainsKey(keyPressed)) {
    885.  
    886.                 #region Clear current sellected data
    887.                
    888.                 // Iterate through and clear the vectors
    889.                 SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    890.                     Destroy(obj.SelectionLine.vectorObject);
    891.                 });
    892.                
    893.                 // First.. clear the selection list
    894.                 SelectedObjects.Clear();
    895.                
    896.                 #endregion
    897.                
    898.                 SelectedObjects.AddRange(SavedSelectedObjects[keyPressed]);
    899.                
    900.                 // Clear the circle selector
    901.                 SelectedObjects.ForEach(delegate(SelectedObjectProperties obj) {
    902.                     Destroy(obj.SelectionLine.vectorObject);
    903.                     obj.SelectionLine = null;
    904.                 });
    905.                
    906.                 _movementPlate.SetActive(true);
    907.                
    908.             }
    909.         }
    910.        
    911.     }
    912.    
    913.     #endregion
    914.    
    915.     #region Helper methods
    916.    
    917.     /// <summary>
    918.     /// Gets the objects in a specific layer
    919.     /// </summary>
    920.     /// <returns>
    921.     /// The objects in layer mask.
    922.     /// </returns>
    923.     /// <param name='mask'>
    924.     /// Mask.
    925.     /// </param>
    926.     GameObject[] GetObjectsInLayerMask(LayerMask mask) {
    927.         GameObject[] goArray = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
    928.         List<GameObject> goList = new List<GameObject>();
    929.        
    930.         for (int i = 0; i < goArray.Length; i++) {
    931.             if ((mask.value  1<<goArray[i].layer) > 0) {
    932.             //if (goArray[i].layer == mask){
    933.                
    934.                 goList.Add(goArray[i]);
    935.             }
    936.         }
    937.         if (goList.Count == 0) {
    938.             return null;
    939.         }
    940.         return goList.ToArray();   
    941.     }
    942.    
    943.     #endregion
    944.    
    945. }
    946.  
    Just a note, the stuff you really want to see starts as line 630
     
  10. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    This is incredible. I'm fiddling around with the code, and learning because everything is commented perfectly. I appreciate it thanks :)
     
  11. Uncasid

    Uncasid

    Joined:
    Oct 5, 2012
    Posts:
    193
    i should note that i use ngui for ui stuff. this system here has 99% of objectbselection / interactions done for you.

    you are welcome
     
  12. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    Ok so now that I look back... Eve online gameplay is basically clicking anywhere on the screen and it moves in that direction, and it keeps going till you hit a button to stop. I was actually talking to a eve developer and he said "In Unity, you could do this by using Camera.ScreenToWorldPoint with some large Z value, then get the direction by doing:
    Code (csharp):
    1. Vector3 moveDir = (worldPoint-shipPosition).normalized;"
    I got the Camera.ScreenToWorldPoint to show the coordinates on the debugger screen, but I'm not sure how to use the vector code.
     
  13. NikoBusiness

    NikoBusiness

    Joined:
    May 6, 2013
    Posts:
    289

    this will help you i think
     
  14. Uncasid

    Uncasid

    Joined:
    Oct 5, 2012
    Posts:
    193
    it is a direction, you can move your ship to that direction by using a lookat / lerping / etc. If you are building an RTS, I would not suggest taking this approach, as it will make controlling ships difficult for the user.
     
    Last edited: Aug 12, 2013
  15. pheekle

    pheekle

    Joined:
    Aug 10, 2013
    Posts:
    12
    In Eve, the double click to move in space is done by getting a direction vector from where you click on the screen. You aren't actually moving to a point, just in a direction.