CodePuppe
CodePuppe

Reputation: 119

Keep the same distance between the camera and a canvas

The idea is to move the camera to a certain point in front of a canvas. I've positioned the camera for the first canvas and I need to maintain this distance when the camera moves to another canvase (the canvases are equal, they just have different positions and rotation angles).

So the question is how to maintain the same camera distance from the canvas centre?

Just to show the idea

Upvotes: 0

Views: 210

Answers (2)

ZayedUpal
ZayedUpal

Reputation: 1601

Put this script on a gameObject(like the camera).
Assign the camera, canvases and distance variable.
Hope this helps:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class CanvasPositioner : MonoBehaviour {
    public Camera cam;
    public Canvas[] canvases;
    public float distance = 15;

    private float xPos;
    private float yPos;
    private float zPos;
    private float angle;

    void PositionCanvases(){
        for(int i = 0; i < canvases.Length; i++){
            angle = canvases[i].transform.eulerAngles.y;
            xPos = cam.transform.position.x + distance * Mathf.Sin(Mathf.Deg2Rad* angle);
            yPos = cam.transform.position.y;
            zPos = cam.transform.position.z + distance * Mathf.Cos(Mathf.Deg2Rad * angle);
            canvases[i].transform.position = new Vector3(xPos,yPos,zPos);
        }
    }
    void LateUpdate () {
        PositionCanvases();
    }
}

Upvotes: 1

Maurice
Maurice

Reputation: 31

This depends on the orientation of the canvas. If you orient them like a square


|__| you could simply place the cam in the exact middleand transform by 90°

If you need a different distance, move them further apart and do it something like this

/ \ | ○ | on the circle in the middle, you can move the camera on the outer edge. The canvas orientation needs to be in parallel to the closest tangent of the circle. You can make it move on the curveline by having an imaginary (or empty gameobject) in the middle and maintain the distance from that.

Upvotes: 1

Related Questions