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. Dismiss Notice

How to convert a vector or direction from camera space to world space?

Discussion in 'Scripting' started by m0nkeybl1tz, Apr 15, 2021.

  1. m0nkeybl1tz

    m0nkeybl1tz

    Joined:
    Feb 10, 2013
    Posts:
    25
    So I know you can use WorldToScreenPoint and ScreenToWorldPoint to convert a point between world and screen space, but what if you want to convert a vector? For example if I move the mouse from the left side of the screen to the right, how would I determine that direction in world space?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,713
    By subtracting the world point of the mouse in its first location from the world point the next frame.

    EDIT: I think Praetor and I have given two completely different answers based on our interpreting your question completely differently.
     
    m0nkeybl1tz likes this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Code (CSharp):
    1. Vector2 screenDir = Input.mousePosition - previousMousePosition;
    2.  
    3. Vector3 worldDir = myCamera.transform.TransformDirection(screenDir);
     
    m0nkeybl1tz likes this.
  4. m0nkeybl1tz

    m0nkeybl1tz

    Joined:
    Feb 10, 2013
    Posts:
    25
    Interesting, I think both of these should work! Thanks ya'll, I think I was trying to overcomplicate it by getting matrix transformations involved...
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    As is tradition.