- Home /
How to successfully transform local mesh vertex coordinates into world coordinates?
Here is what I'm trying to do. I load the mesh and randomly access a vertex from the mesh and extract it from the array. I then want to transform this vertex's location to world coordinates so that I can use it to move another game object in the scene to that location on the first object.
My code works, and even the scaling is alright I'm fairly certain, but the transformed coordinates are off by roughly +8 in the X direction and -12 in the Z direction.
Why is this happening? Here is my code:
using UnityEngine; using System.Collections;
public class Path : MonoBehaviour {
GameObject model;
public
void Start ()
{
model = Resources.Load("Model") as GameObject;
Vector3[] vertices = model.GetComponent<MeshFilter>().sharedMesh.vertices;
var myIndex1 = Random.Range(0, vertices.Length);
Vector3 p = vertices[myIndex1];
print(p);
Transform tr = model.transform;
Vector3 V = tr.TransformPoint(p);
print(V);
iTween.MoveTo(gameObject, V, 15);
}
void Update () {
}
}
Answer by FortisVenaliter · Jan 27, 2016 at 07:08 PM
You're using model.transform to convert it into World Coordinates. But model comes from Resources, which means it's a prefab, which means it isn't in the scene, which means it doesn't have true local coordinates. Are you sure you don't want to use the local object's transform instead?
Thank you for the helpful reply. You are correct, and what you said makes a lot of sense. This script is attached to GameObject1 because it is the script that will make it move in the game. However, I need the local coordinates of another object, GameObject2 in the scene first.
Is there a way I can access GameObject2's local transform using this same script attached to GameObject1?
Or is there a way I can send information across scripts so that I could attach a script to GameObject2 and to retrieve and then send the coordinates to GameObject1's script?
Sure. You just need to add a class variable for the second GameObject, and then assign it in the inspector. Then you can use that reference to get the transform and apply whatever math you need.
Sorry if this is noobish, I'm still learning here! xD
How would I do this with an object that is spawning in at run time from the prefab I mentioned earlier? Also, how do I assign class variables in the inspector?