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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Move object opposite to Mouse position

Discussion in 'Scripting' started by Keysaw, Jan 12, 2016.

  1. Keysaw

    Keysaw

    Joined:
    Oct 14, 2015
    Posts:
    19
    Hello !

    I would like to achieve something a little bit special by script.

    Basically, I have a sphere object in my scene. I would like this sphere to move in the opposite direction of the mouse, in screen view.

    It's pretty hard to explain, so here's an exemple : http://studiokraftwerk.nl/

    If you look at this website's background, some "dots" are moving when we get the mouse over it. This is the effect I would like to achieve. If anyone have an idea of how I can do that... I would love it!

    Here's how I get the distance between the mouse and the object, in screen space (but again, I'm not sure that I did it the right way...).
    Code (CSharp):
    1. void Update ()
    2.     {
    3.         // Mouse effect
    4.         Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, transform.position.z);
    5.         Vector3 vertexPos = mainCamera.WorldToScreenPoint (new Vector3 (transform.position.x, transform.position.y, transform.position.z));
    6.  
    7.         if (Vector3.Distance (mousePosition, vertexPos) < 30)
    8.         {
    9.             Debug.Log ("MOUSE: " + mousePosition + "   DOT: " + vertexPos);
    10.         }
    11.     }
    But I can't figure out how to make the object move smoothly, and then go back to it's position when the mouse is out of range.

    Thank you in advance!
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,745
    In Start(), store vertexPos, and that never changes - that's where you'll return, and that's where all your math will be based from.

    After that, one tool you will definitely want to use (vertexPos - mousePosition).normalized (the direction in which you'll move - normalized will make this 1 unit long, which you can effectively multiply).
     
  3. Keysaw

    Keysaw

    Joined:
    Oct 14, 2015
    Posts:
    19
    Thank you for that, it's almost working perfectly!

    Another thing that came to my mind : do you have any idea of how I can make a "dot-line" shape like that by script ? I tried different things, but this isn't really effective...