Hey guys, I’m working on my first real unity app, well doing experiments to get all the necesary bits in place anyway.
My view will essentially be side scrolling so I’m trying to figure out how to take the 2d screen coordinates from a finger tap and convert them to the proper point in 3d space.
I’d like to tap anywhere on the screen and find the proper position in 3d space that is on the same z-position as my player avatar but has the proper x, y coordinates.
I’m trying to calculate the distance along the x,y axis between the spot tapped by the finger and the avatar. Assuming both are on the same z location.
In everything I’ve done so far I’ve always been tapping and clicking on objects in which case I use a ray to get the answer I need. But this time I’m tapping on thin air and I’m not sure how to proceed.
You already have the Z-value; it’s the same as your character.
If you are working in 2D just decide a value for the axis you aren’t using and keep it at that.
For instance, you are using the XY-plane for your game. Set Z to an arbitrary value, 0 for instance, and just work with X and Y. You press “insert random point on screen”, grab the X and Y value from the input and do whatever it is you want to do with them in regards to controlling the character.
If your concern is about moving the character using some operation that uses Vector3, just create a Vector3 and set the axis you aren’t using to the value you decided upon from start.
Vector3 vec = new Vector3(input.x, input.y, 0);
Vector3 vec = new Vector3(input.x, input.y, hero.transform.position.z);
I would personally use the first option since it’s cheaper.
Calculating the distance is done through the .magnitude or .sqrMagnitude of the respective Vector class. Or if you’re only interested in the distance in each respective axis you just do something along the lines of
float xDistance = input.x - hero.transform.position.x
(might want to do a Mathf.Abs on that).
Thanks a lot, I’ll try this out tonight. Also completely random but seeing Enercities and the Paladin studios website is what inspired me to get into Unity a while ago!
What if I have a player Sprite on a plane in my scene. And I want to get the coords of the playerSprite origin then compare them to the position of the mouse.
Should I cast a ray from the origin of the player sprite to the camera? Or should I use this rayCast method and compare the two vectors?
I feel like it’d be easier for my project in the long run to use pixel coords instead of world space.