- Home /
How do I get the direction of an objects face?
Not the direction an object is facing but say the face of a cube. I would like to instantiate an object with is rotation appropriated the the face I clicked on. My idea is to set the 'object I want to instantiate's current direction to up and have it point away from the object (in theory).
Here is what it looks like currently as an example.
As you can see I would like the middle node to be facing right relative to the player.
here is my code.
// Update is called once per frame
void Update()
{
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, toolRange))
{
Debug.DrawRay(transform.position, (hit.point - transform.position), Color.yellow);
if (Input.GetMouseButtonDown(0))
{
var node = Instantiate(wireNodePrefab, hit.point, quaternion.identity) as GameObject;
}
}
}
Code may or may not be useful but its here if you think it will help me.
While I work through the night any help will be greatly appreciated!
Answer by mysterion · Aug 13, 2021 at 11:22 PM
So I finally got it. I was working too hard with tools I didn't need. Here is my solution.
var pointToLook = Quaternion.FromToRotation(Vector3.up, hit.normal);
var node = Instantiate(wireNodePrefab, hit.point, pointToLook) as GameObject;
Answer by Namey5 · Aug 13, 2021 at 07:33 AM
You can use the normal of the hit point to get the direction of its face;
GameObject node = Instantiate (wireNodePrefab, hit.point, Quaternion.LookRotation (hit.normal));
I spent a few hours last night playing with Quaternion.LookRation. It has two parameters. I believe it is the right idea but I need to get the math right. The second argument you would pass is to tell the function which way is up. I've even changed the normal orientation of the prefab. Edit* And I have tried hit.normal seems to be on the right track for me as well. Maybe my problem is that in not setting the forward direction in the prefab correctly.
Edit2* After hours of work I got it and it was soooo simple. Thanks for offering your help.