0

I have a triangle defined by 3 points (System.Numerics.Vector3, I'm not using Unity3d):

A [-0,21090554, 3,81115985, -23,54532623]

B [0,01877949, 3,79133320, 23,49146652]

C [33,08344650, 1,99846101, 0,20934258].

As you can see triangle is slightly tilted and is not parallel to the ground:

enter image description here

I need to rotate the triangle so it will become parallel to the ground (all three points Y coordinates will become the same).

So I need to calculate a rotation to align triangle normal with world up vector [0, 1, 0] (vertical normal on my picture is [0, 10, 0] because [0, 1, 0] vector will be too short to see and to distinguish it from the triangle normal).

I'm new to 3D and have no idea how to calculate a rotation (Quaternion or Matrix I guess) and apply it to all triangle points.

halfer
  • 19,824
  • 17
  • 99
  • 186
bairog
  • 3,143
  • 6
  • 36
  • 54

2 Answers2

1

You can use Quaternion.CreateFromAxisAngle to create the quaternion.

var normal = Vector3 Normalize((A - B) * (C - B));
var toDir = Vector3.UnitY;
var axis = normal * toDir;

var angle = Math.Acos(Vector3.Dot(normal, toDir));

var rot = Quaternion.CreateFromAxisAngle(axis, angle);

To rotate the 3 points, you need define an origin first, then use Vector3.Transform transform the points by the quaternion.

var O = (A + B + C) / 3;
var Ar = Vector3.Transform(A - O, rot) + O;
var Br = Vector3.Transform(B - O, rot) + O;
var Cr = Vector3.Transform(C - O, rot) + O;
shingo
  • 18,436
  • 5
  • 23
  • 42
  • Thank you for your code. But I use **System.Numerics**. And [Quaternion](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.quaternion) from that library differs from Unity3d [Quaternion](https://docs.unity3d.com/ScriptReference/Quaternion.html) - it has no **FromToRotation**. Sorry for misleading - I will update my question. – bairog Feb 15 '23 at 06:59
  • Sorry for this, I have updated the answer using System.Numerics. – shingo Feb 15 '23 at 07:41
  • On the `var angle = Math.Acos(Vector3.Dot(N, toDir))` line **N** should be changed to **normal**, right? – bairog Feb 15 '23 at 08:01
  • Yes N is normal. BTW if you find the result is not good, try to reverse the normal. – shingo Feb 15 '23 at 08:45
  • I've invited you [to chat](https://chat.stackoverflow.com/rooms/252336/room-for-bairog-and-shingo) (to ask some more questions) - maybe you can help me. Thank you. – bairog Mar 07 '23 at 04:39
0

Consider the Cross Product between the vertical and triangle normal.

  • Direction of the Cross Product becomes direction of your rotation axis.
  • From definition of Cross Product, you can obtain the info(sin value) about the rotation angle.

Now, you have axis and angle. So, you can represent the rotation as Quaternion or some other representation.

fana
  • 1,370
  • 2
  • 7