how to make a function that like camera.WorldToScreenPoint?

I am implement “projected grid” method to optimize my game.

In project grid algorithm, it need to project four corner point(0,0) (1,0 ) (1,1) and (0,1) to world space and use these value to parameterize a plane.

so, I need w component to scale each paeameterize point in correct place.

worldToScreenPoint or ScreenToWorldPoint can transform point to 3d space correctly, but the w component is always equal to 0. So, I need to implement some functions that transform 3d point to screen space coordniate or inverse it to get world space point.

I can get or build model, view and projection matrix by

Matrix4x4 model = Matrix4x4.TRS(transform.position, transform.rotation, transform.localScal);
Matrix4x4 view = mainCamera.worldToCameraMatrix;
Matrix4x4 projection = mainCamera.projectMatrix;

Matrix4x4 mvp = projection * view * model;
Vector4 result = MatrixHelper.MultiplyMatrixAndVector4(mvp, v);

But, the result is not same as WorldToViewportPoint.

Now, I figure out that I have some mistake in this transform.

After transform, I need to normalize the result by (result + 1f) * 0.5f.

But, after this processing, result still have little different to WorldToViewportPoint.

So, I want to know how to transform a world space point to screen coordniate that the transforming result is same as WorldToViewportPoint.

A w component of “1” tells you that the returned vector is a position and not a direction (in which case it would be “0”). WorldToScreenPoint actually returns a Vector3 so it doesn’t have a w component. Unity can implicitly cast it to a Vector4 in which case the w component is set to 1

Your question is way too unspecific. Return “something” doesn’t make any sense.

Anyway you can always wrap the function in your own function:

// C# extension method:
public static Vector4 WorldToScreenPointAndSomething(this Camera aCam, Vector3 aPos)
{
    Vector4 result = aCam.WorldToScreenPoint(aPos);
    result.w = something;
    return result;
}