Linear equations in Unity?

Hey,

does anybody know a library/functions how to solve linear equations in Unity? My previous search just found old results, that basically suggest there weren’t many working options :confused:

Because for my current project I would like to calculate the hitpoint on a plane in 3D space and get that hitpoint in relative coordinates to the plane, to use it for ViewportPointToRay Raycast afterwards.

I was hoping I can solve it myself by getting the hitpoint and the planes 3-corner points then getting 3 equations with 2 variables, which should be solvable by itself. Unfortunately for whatever reason, the hitpoint I receive is not on the plane of the 3 corner points of the plane, but behind it. (I am getting the cornerpoints by the meshes Vertice List and am using a Mesh Collider on the plane… so idk why that’s the case).

Anyways it should still b
e solvable, as I know the 2 Points of the line and can see it is intersecting with the Debug.DrawLine, so I would just get that line and check for the intersection point with the plane, but the math is a little more complicated then. Or I can’t think of an easy way, because I have never been that good with math D:

So I look forward for any suggestions! :slight_smile:

Well, it seems you’ve gone a bit too far here ^^. Solving linear systems of equation by a human is a pretty trivial process. Even it’s fundamentally the same process, a computer generally works with predefined formulas / algorithms. However solving a system of linear equation requires rearrangement of the equations.

The most straight forward way is to represent your equations with an augmented / extended matrix and use gaussian elimination.

However a simple vector - plane intersection can be calculated with simple vector math. Unity actually provides you two structs which encapsulate those simple tasks. Specifically the Plane and Ray struct. The plane struct has a Raycast method which gives you the distance of the intersection along the ray. So you can simply use Ray.GetPoint to get the intersection point.

If you’re interested in the math behind those methods, just have a look at the reference source code for the Raycast method and the GetPoint method.

Note that the Raycast method does only detect a hit (returns true) when the ray hits the “front side” of the plane. Though the intersection distance should also work backwards as long as your ray is not parallel to the plane surface.

Thanks :slight_smile:
I didnt know about the Plane struct, I will see if it returns the accurate result! :slight_smile:

Otherwise I also manged to import math.NET, which should help doing the math, if needed!