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

Question ScreenToWorldPoint problem

Discussion in 'Scripting' started by sailence, Nov 21, 2020.

  1. sailence

    sailence

    Joined:
    Sep 2, 2018
    Posts:
    3
    hello i am a beginner and that is my script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class arme : MonoBehaviour
    6. {
    7.    
    8.     public Transform objectToFollow;
    9.     public Vector3 offset;
    10.  
    11.     void Update()
    12.     {
    13.         transform.position = objectToFollow.position + offset;
    14.         mouseTracker();
    15.     }
    16.  
    17.     private void mouseTracker()
    18.     {
    19.         Vector3 MousePosition = Input.mousePosition;
    20.         Vector3 MousePositionWorld = Camera.main.ScreenToWorldPoint(MousePosition);
    21.         print(MousePositionWorld);
    22.     }
    23. }
    24.  
    the program should return me the value of "MousePositionWorld" thanks to ScreenToWorldPoint according to MousePosition,
    the problem is that as soon as I launch the program, the variable "MousePositionWorld" does not change, it does not come from "MousePosition" because I tested it and it changes well depending on the mouse unlike "MousePositionWorld", the last line with the "print" also works because I tested it.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,833
    Input.mousePosition is a Vector2, but ScreenToWorldPoint operates on a Vector3. If you take a Vector2 and try to use it as a Vector3, Unity will let you, but it automatically fills in the third coordinate with zero.

    ScreenToWorldPoint interprets the third coordinate as "how far away from the camera" you want to go. So you are going "zero" far away from the camera, which means you just get the camera's position, no matter which direction you try to go in.

    You should fill in a more sensible value for the third coordinate.
     
    Kurt-Dekker likes this.
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @sailence

    What kind of Camera setup you have? Orthograpic or Perspective?
     
  4. sailence

    sailence

    Joined:
    Sep 2, 2018
    Posts:
    3
    its perspective and thank you antistone i will try this tomorrow