- Home /
How to get the y coordinate of a point based on the x and z coordinates
So basically I am working on a game at the moment and I have a random object spawner which spawns the object randomly on the plane, this worked before as I had a simple plane set at a y of 3, now I received a new plane .obj which is sloped and has different y values at different points, and so the spawner does not work any more. My question is how can I get the y position of a point based on the x and z coordinates and based on the returned y position spawn the object. I was thinking of raycasting but from what I can tell it does not return the Y value when it hits something. Is there any way to do this or would I have to change the terrain and set a specified Y pos for each section of the terrain.
Thank you.
Answer by tanoshimi · Jul 19, 2014 at 07:53 PM
What's wrong with raycast? The point property of the raycasthit gives you a Vector 3 in world space, so you can take the y coordinate straight from that: http://docs.unity3d.com/ScriptReference/RaycastHit-point.html
Answer by rutter · Jul 19, 2014 at 08:00 PM
If you think about it abstractly, an x-coordinate specifies "some distance to the right", and a z-coordinate specifies "some distance forward".
So this:
Vector3 v = new Vector3(x, 0, z);
Is the same as:
Vector3 v = Vector3.right * x + Vector3.forward * z;
The above uses "world space". Every object in Unity has a transform component, which keeps track of its position, rotation, and scale. The transform also allows you to convert between world space and "local space" (relative to that specific transform).
So you could use something like this:
Vector3 v = transform.TransformPoint(x, 0, z);
Or:
Vector3 v = transform.position + transform.right * x + transform.forward * z;
All of this assumes that the transform's opinion of "right" and "forward" agrees with what you're expecting. If they don't, it's simple enough to switch around the axes:
Vector3 v1 = new Vector3(0, x, z); //for example
Vector3 v2 = transform.TransformPoint(v1);
You'll also need a reference to the plane's very own transform. Maybe that's the same transform your script is attached to, or maybe you need to set up a reference in the inspector. There are plenty of tutorials to help with that bit, if you need.
Your answer
Follow this Question
Related Questions
Instantiated Objects not being set at ground/terrain level?(Solved) 1 Answer
Building placement validation on curved terrain 0 Answers
using Raycast.hit function my car gets up and doesnt gets down ? it is in flying state 1 Answer
Flattening terrain under my object at start() 1 Answer
Have object follow mouse on terrain 1 Answer