This is a follow-up on the following thread.
I'm applying a code that will move an object just outside the camera's frustum. I have used the same code in other projects, and it worked fine.
However, I'm using it with URP now, and I'm experiencing a z-position change while I expected only a x position change.
And I just don't see why it does that.
I have recorded a video here.
If I press the button, the cube should be moved to the left only. But it also moves to the back (z position).
And this is the script that I have applied to the cube in the video:
using System;
using UnityEngine;
public class PlaceOutsideCamera : MonoBehaviour
{
public void PlaceOutsideFrustum(Transform uTransform, bool uLeft)
{
uTransform.position = pPlaceOutsideFrustum(uTransform, uLeft);
}
public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft)
{
var frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
Ray ray;
Plane plane;
if (uLeft)
{
// 1.
ray = Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight / 2f, 0));
plane = frustumPlanes[0];
}
else
{
ray = Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth - 1, Camera.main.pixelHeight / 2f, 0));
plane = frustumPlanes[1];
}
float fDistance = Mathf.Abs(Camera.main.transform.position.z - uTransform.position.z);
// 2.
var borderPoint = ray.GetPoint(fDistance);
// 3.
var frustumOutside = -plane.normal;
Bounds b = BoundsFromTransform(uTransform);
// 4.
var halfDiameter = b.size.magnitude / 2f;
return borderPoint + frustumOutside * halfDiameter;
}
public static Bounds BoundsFromTransform(Transform uTransform)
{
try
{
Bounds bounds = new Bounds(uTransform.position, Vector3.zero);//wir hätten auch einfach new Bounds() nehmen können, meint Manfredas
foreach (Renderer renderer in uTransform.GetComponentsInChildren<Renderer>())
{
bounds.Encapsulate(renderer.bounds);
}
Vector3 nOff = bounds.center - uTransform.position;
return new Bounds(nOff, bounds.size);
}
catch (Exception ex)
{
UnityEngine.Debug.Break();
return new Bounds();
}
}
public void OnGUI()
{
if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!"))
{
pDoThis();
}
}
private void pDoThis()
{
this.PlaceOutsideFrustum(this.transform, true);
}
}
Can anybody tell me why my code does this? I just don't see it. Thank you very much for the help!
Edit: Here is another video that shows the camera position in the Inspector.