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

Controlling 3D-object with mouse on Z and X-axis

Discussion in 'Scripting' started by saturnuns-ringar, Apr 27, 2022.

  1. saturnuns-ringar

    saturnuns-ringar

    Joined:
    Apr 26, 2022
    Posts:
    12
    Howdy,

    I'm completely new to Unity and I got stuck at an early point: I'm trying to control an object with the mouse, on the Z and X-axis. But I can't get this right.

    This is the closest I have so far, and as far as I can remember it worked ok. For a while. Not anymore though.

    Code (CSharp):
    1.  
    2. public class Player : MonoBehaviour
    3. {
    4.        private int mouseSensititvity = 50;
    5.  
    6.        void Update()
    7.        {
    8.              Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(
    9.                    Input.mousePosition.x, Input.mousePosition.y, 1.0f ));
    10.              Debug.Log("mousePos.x: " + mousePos.x);
    11.              Debug.Log("mousePos.y: " + mousePos.y);
    12.              transform.position = new Vector3(mousePos.x * mouseSensititvity, 0,
    13.                    (mousePos.y * mouseSensititvity) - mouseSensititvity);
    14.              Debug.Log(transform.position);
    15.        }
    16. }
    17.  
    18.  
    19.  
    20.  
    It doesn't work very well. o_O The Debug.Log of "mousePos.y" is something like 9.4... at the center of the screen now. The x-position is 0 though.

    Thanks for any help on this one!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    ScreenToWorldPoint is not really the right tool for this. I recommend Plane.Raycast:

    Code (CSharp):
    1. void Update() {
    2.   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3.   Plane p = new Plane(Vector3.up, Vector3.zero);
    4.   if (p.Raycast(ray, out float enter)) {
    5.     Vector3 worldPos = ray.GetPoint(enter);
    6.     transform.position = worldPos;
    7.   }
    8. }
    Not sure how "mouse sensitivity" would be relevant here. Unless you're not trying to use the mouse position and instead just move the object according to the mouse deltas. In that case you'd do something like this:

    Code (CSharp):
    1. float sensitivity = 50f;
    2.  
    3. void Update() {
    4.   Vector3 diff = new Vector3(Input.GetAxis("Mouse X"), 0, Input.GetAxis("Mouse Y"));
    5.   diff *= sensitivity;
    6.   transform.position += diff;
    7. }
     
  3. saturnuns-ringar

    saturnuns-ringar

    Joined:
    Apr 26, 2022
    Posts:
    12
    This worked like a charm. Thanks! Nice profile picture btw.