- Home /
Get face normal and get its local Euler Angles?
I have a simple script which checks using raycast and gets mesh face normals and what I want to do is to get it's local rotation so i can make my object rotated alike... is that possible? Here's the code I'm using to get face normals:
private var Target : Transform;
var Hit : RaycastHit;
var layerMask = 1<<8;
private var faceNormalZ : float = 0;
private var faceNormalX : float = 0;
function Start () {
Target = GameObject.FindWithTag("Player").transform;
}
function Update (){
transform.position = Target.position;
transform.localEulerAngles.y = Target.localEulerAngles.y;
transform.rotation.x = faceNormalX;
transform.rotation.z = faceNormalZ;
if (Physics.Raycast(transform.position, Vector3.down, Hit, 2, layerMask)){
var meshCollider = Hit.collider as MeshCollider;}
if (meshCollider == null || meshCollider.sharedMesh == null)
return;
var mesh : Mesh = meshCollider.sharedMesh;
var vertices = mesh.vertices;
var triangles = mesh.triangles;
var normals = mesh.normals;
P1 = vertices[triangles[Hit.triangleIndex * 3]];
P2 = vertices[triangles[Hit.triangleIndex * 3 + 1]];
P3 = vertices[triangles[Hit.triangleIndex * 3 + 2]];
center = ((P1 + P2 + P3) / 3);
P1 = normals[triangles[Hit.triangleIndex * 3]];
P2 = normals[triangles[Hit.triangleIndex * 3 + 1]];
P3 = normals[triangles[Hit.triangleIndex * 3 + 2]];
faceNormal = ((P1 + P2 + P3) / 3);
faceNormalZ = faceNormal.z;
faceNormalX = -faceNormal.x;
}
Answer by Berenger · Jun 06, 2012 at 03:01 PM
(Theory) You can't know the rotation of a vector, because it doesn't make sense. It need to be relative to something. You might need confirmation of someone good in math, but I think there is an infinity of rotation from a vector to another, so I think you need 2 relative vectors.
Anyway, you probably want to use Quaternion.LookRotation.
Answer by Mortoc · Jun 06, 2012 at 02:55 PM
You don't have to dig in to the mesh for this, you can just use:
someObject.transform.position = Hit.position;
someObject.transform.up = Hit.normal;
well, not really as it won't give me "face" normal but Hit.point normal so if my raycast will hit another object under an angle then my object will rotate to that angle and not to face normal :/
Ah right, I misread the problem. You can still calculate the face normal by:
Vector3.Cross(p2 - p1, p2 - p3).normalized
and then set someObject.transform.up to the result of that
Answer by DHARMAKAYA · Nov 08, 2016 at 03:31 PM
Stop capping the first letter of vars!!!!! THAT IS THE PROBLEM HERE!!!!
(shaking fist in air)
Haha, this question was asked 4 years ago, I've improved my C# coding skills by just "a lot" since then, dw :))