Search Unity

Resolved Teleport an object to mouse position

Discussion in 'Scripting' started by Fishinapool, Oct 11, 2020.

  1. Fishinapool

    Fishinapool

    Joined:
    Mar 16, 2020
    Posts:
    22
    So i tried this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Mouse : MonoBehaviour
    6. {
    7.  
    8.     public GameObject MousePosGameObject;
    9.  
    10.     Vector3 worldPosition;
    11.  
    12. void Update()
    13.     {
    14.         Vector3 mousePos = Input.mousePosition;
    15.         mousePos.z = Camera.main.nearClipPlane;
    16.         worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
    17.  
    18.         MousePosGameObject.transform.position = new Vector2(worldPosition.x, worldPosition.y);
    19.     }
    20.  
    21. }
    But it the object almost doesn't move at all.
     
  2. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    676
    At Line 18, you are assigning the MousePosGameObject's z coordinate to be zero. Assuming your camera is at the default z=-10, that's going to do just what you are seeing: the object will move, but not very much, because it is far away from the camera, and perspective foreshortening is going to make it seem to stay close to the origin in world space.

    Are you trying to make the object stay at its original distance from the camera, but move to a point near where the mouse cursor is?
     
  3. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    676
    Try this:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Mouse : MonoBehaviour
    4. {
    5.     public GameObject MousePosGameObject;
    6.  
    7.     void Update()
    8.     {
    9.         Vector3 mousePos = Input.mousePosition;
    10.         mousePos.z = MousePosGameObject.transform.position.z - Camera.main.transform.position.z ;
    11.  
    12.         MousePosGameObject.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
    13.     }
    14. }
     
    ClumsyCaden likes this.
  4. Fishinapool

    Fishinapool

    Joined:
    Mar 16, 2020
    Posts:
    22
    thanks i haven't tried it but i will try it later
     
  5. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    676
    Let me know how that goes. I think part of your problem is that it is not obvious that the Z coordinate given to ScreenToWorldPoint is actually not a coordinate: it is the distance from the camera.
     
  6. Fishinapool

    Fishinapool

    Joined:
    Mar 16, 2020
    Posts:
    22
    Sorry for the late reply, but it worked! Thank you so much!
     
    Stevens-R-Miller likes this.
  7. ClumsyCaden

    ClumsyCaden

    Joined:
    Mar 14, 2020
    Posts:
    2
    Thanks! It worked for me :D