Input.mousePosition to World converts to Camera's position, No matter where I click
I want the script to draw a line between two positions, the position of the object the script is on and the position of where I clicked the mouse, without Raycasting
Vector3 spawnPos = transform.position;
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.DrawLine(spawnPos, mousePos, Color.black);
Draws the line in the picture above.
Outdated Code
IEnumerator SimulateProjectile() { Vector3 spawnPos = new Vector3(transform.position.x, transform.position.y + 1f, transform.position.z); //or basically Transform.position Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f)); //or Camera.main.ScreenToWorldPoint(Input.mousePostion); Debug.DrawLine(spawnPos, mousePos, Color.black); //draws line between the two positions yield return null; }
Look at the Scripting API. It statesd that the z value of the Vector corresponds to the distance from teh camera. So, it's no wonder why with a z valuie of 0, the returned Vector3 is equal to the camera's position. I think you might want to use Raycasting ins$$anonymous$$d, however, to get a the position on the surface where your cursor is pointing at.
No it's not, the same thing happens when you do Camera.main.ScreenToWorldPoint(Input.mousePosition) ins$$anonymous$$d of it.
Plus I'm not planning to use it for getting a position on the surface, I simply added it in this scene for a sense of space.
Answer by Mister-Mortal · Nov 23, 2016 at 01:40 PM
You are using Camera.main.ScreenToWorldPoint() wrong. You need to calculate correct z value for the Vector3 parameter. Because you are passing 0f for z it calculates world position 0f units away from camera, which, because of math reasons, always happens to be position of camera.
It's pretty easy to calculate correct z value, here's the example:
Camera.main.ScreenToWorldPoint(new Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
-Camera.main.transform.position.z + zPositionOfThePlane));
I rephrased my question, my apologies I wasn't clear when I asked.
Your answer
Follow this Question
Related Questions
Issue with getting the mouse position in 3D and moving a gameobject on the y & z axis 0 Answers
How do I draw a raycast with my mouse position that is relative to the main camera? 0 Answers
Help with middle mouse panning / dragging 0 Answers
ScreenPointToRay generate wrong ray because camera have a parent with transform 0 Answers