- Home /
Get Camera mouse position not working correctly in 2D space
Hi!
I have this script that should move a cube to the mouse position but it just moves around in the middle.
Here's my code.
Vector3 mousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector3.forward);
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Hit " + hit.transform.gameObject.name);
Instantiate(mouseTest, hit.point, Quaternion.identity);
}
mouseTest.transform.position = mousePos;
I can't really see something wrong with it. Please tell me what is wrong!
Thanks
Answer by Eric5h5 · Jan 24, 2015 at 07:09 PM
You're using ScreenToViewportPoint for no reason. Viewport space is normalized from 0..1, and is only used for the old GUIText/GUITexture objects.
I see. I tried changing it to "Vector3 mousePos = Camera.main.WorldToViewportPoint(Input.mousePosition);". Now it is kinda following the mouse. It is just offset a bit above and to the right. How can I fix this?
EDIT: Never$$anonymous$$d. It is not functioning as I thought it was.
Answer by Bentley · Jan 24, 2015 at 08:01 PM
What you're looking for is Camera.main.ScreenToWorldPoint(), not Camera.main.ScreenToViewportPoint(). Also you don't need the Raycast if you're just using it for instantiation. You can simply instantiate it to mousePos instead of hit.point.
Hope this helps,
Bentley
@Bently I need it to raycast because of some reasons. When I use Camera.main.ScreenToWorldPoint() it moves it to like around 400 for some reason.
In that case you could try this:
Vector3 mousePos = Input.mousePosition;
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenPointToRay(mousePos));
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Debug.Log("Hit " + hit.transform.gameObject.name);
Instantiate(mouseTest, hit.point, Quaternion.identity);
}
mouseTest.transform.position = mousePos;
Your answer
Follow this Question
Related Questions
How do I drag a sprite around? 2 Answers
2d character, how to limit rotation to z, with character looking left? 0 Answers
Why is Input.mousePosition returning wired values using Cinemachine 2D with dynamic following? 0 Answers
How to make gun rotate around player based on mouse position 2 Answers
How to stop an object of going to far 2 Answers