0
\$\begingroup\$

I'm using the next code to move an objecto into an isometric projection (30/45)

[SerializeField] private Camera cam;
[SerializeField] private Transform target;
[SerializeField] private float speed;

private Vector3 forward, right;

private void Start()
{
    forward = cam.transform.forward;
    forward.y = 0;
    forward = Vector3.Normalize(forward);
    right = Quaternion.Euler(0, 90, 0) * forward;
}

private void Update()
{
    if (Input.GetKey(KeyCode.Mouse0))
    {
        var righMovement = right * speed * Time.deltaTime * (Input.GetAxis("Mouse X"));
        var upMovement = forward * speed * Time.deltaTime * (Input.GetAxis("Mouse Y"));

        if (righMovement != Vector3.zero && upMovement != Vector3.zero)
                target.forward = Vector3.Normalize(righMovement + upMovement);

            lastPosition += new Vector3
            {
                x = righMovement.x + upMovement.x,
                y = righMovement.y + upMovement.y,
                z = righMovement.z + upMovement.z
            };

            target.position = lastPosition;

            //target.position = Clamp(lastPosition);
        }
    }
}

At same time I want to clamp that object based on the screen size to avoid move the target when is off screen, so I made this:

private Vector3 Clamp(Vector3 position)
{
    var w2p = Camera.main.WorldToViewportPoint(position);

    w2p.x = Mathf.Clamp(w2p.x, .2f, .8f);
    w2p.y = Mathf.Clamp(w2p.y, .2f, .8f);

    return Camera.main.ViewportToWorldPoint(w2p)
}

But I'm getting some weird behaviours, the X axis clamp is fine, but Z is not working at all, and Y is on move what is not ok. It's quite probable I'm doing this in the wrong way. How it should be?

\$\endgroup\$
0
\$\begingroup\$

https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html

all you need is this link. in perspective we dont have axact bound but we have bounds in distance. you have to calculate camera distance from you object and calculate bound on that distance.

if its in 3d you can calculate using below:

 public static class CameraExtensions
 {
     public static Bounds OrthographicBounds(this Camera camera)
     {
         float screenAspect = (float)Screen.width / (float)Screen.height;
         float cameraHeight = camera.orthographicSize * 2;
         Bounds bounds = new Bounds(
             camera.transform.position,
             new Vector3(cameraHeight * screenAspect, cameraHeight, 0));
         return bounds;
     }
 }

you can follow this thread for more info:

https://answers.unity.com/questions/501893/calculating-2d-camera-bounds.html

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I forgot to say this camera is orthographic \$\endgroup\$ – Lobsang White Aug 24 '19 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.