- Home /
Rotation Transform to face character AND normal to terrain
Hello, I would need a little help concerning the rotation of an object so that it is positioned at the normal of the ground but also towards the camera (or the character).
I'm really bad as soon as angles come into play ...
I think you will understand better with the following image:
on the left, what I managed to do with the following code:
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
int layerMask = LayerMask.GetMask("Ground");
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
drag.transform.position = hit.point;
drag.transform.up = hit.normal;
}
on the right image what I wish I had.
The object is a child of the character, I don't know if that can help for the calculations.
I added a grid so that you can see the deformation of the terrain.
I hope I have managed to get you to understand me and I thank you very much for your help in advance
Answer by Namey5 · Jun 21, 2020 at 11:18 PM
The quaternion LookRotation constructor takes a forward vector and an optional up vector, so we can use that to set the object's rotation directly ('player' is just whatever object you want it to look at);
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
int layerMask = LayerMask.GetMask("Ground");
Vector3 up = Vector3.up;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
drag.transform.position = hit.point;
up = hit.normal;
}
Vector3 forward = (player.transform.position - drag.transform.position).normalized;
drag.transform.rotation = Quaternion.LookRotation (forward, up);
Answer by Nosferator · Jun 22, 2020 at 05:11 PM
Thank you very much @Namey5 , it works perfectly. I just tweaked it a bit because I just wanted a direction not really "around" the character.
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
int layerMask = LayerMask.GetMask("Ground");
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
drag.transform.position = hit.point;
drag.transform.up = hit.normal;
drag.transform.rotation = Quaternion.LookRotation(character.transform.forward, drag.transform.up);
}
Do you think is possible to rotate the object on itself with a fixed angle but that it always keeps the same direction as in the previous script?
I would also like to bring the object out of the ground but I think I'll find something on the forum.
thank you very much again
Your answer
Follow this Question
Related Questions
Bound the gameobject from the ground 1 Answer
Bake terrain normal via script 0 Answers
Making a particle effect parallel to the slope of a terrain 1 Answer
How to handler rotation of a Gameobject while aligning it with normals 1 Answer
hit.normal rotation problem, help please really confused 1 Answer