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

how to make an object follow the mouse in the x and z axis but not y?

Discussion in 'Physics' started by StephenRJudge27, Mar 8, 2017.

  1. StephenRJudge27

    StephenRJudge27

    Joined:
    Sep 2, 2015
    Posts:
    24
    Hello, I am trying to have an object follow the mouse in x and z space while maintaining the same position.y.
    How do you think I would be able to do this?
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    At what angles would the camera be pointed? Depending on the allowed orientations of the camera, the answer to this changes, partly because of the fact that if it's a fixed angle then there are probably some shortcuts that could be taken, and partly because some angles could cause some cursor positions on the screen to have undefined solutions based on the initial y-position of the object in question.

    I'm imagining a world that is only an x-z plane and a movable object that is somewhere on that plane (y = 0), with a view that shows both the plane and the "sky". If the cursor is placed somewhere over the plane, then the object can move to that spot on the plane. If the cursor is placed over the "sky", then there is no solution-- this would need to be handled somehow in your logic, probably by giving a different rule for where to place the object in this case.

    I think the most general answer to your question is: Given a ray AB obtained from Camera.ScreenPointToRay() and a y-position yo, the object should be moved to the point that intersects with AB at y = yo. Another way of looking at it is to find the position where the ray AB intersects the plane defined by y = yo.

    Finding a ray-plane intersection is luckily pretty easy, especially if the plane is oriented with one of the world planes, but it's even easier if the ray and plane are always rotated the same way, which is, again, one reason I'm curious about the camera.

    It's not too crazy that I've maybe missed a more straightforward way to do this sort of thing using Unity methods (something in Camera, Vector3, or Mathf maybe). If so, I'm hoping someone else will chime in.
     
  3. StephenRJudge27

    StephenRJudge27

    Joined:
    Sep 2, 2015
    Posts:
    24
    Thank you for your reply I will try to test that out. The camera is an orthographic camera and the angle is 35 degrees.