Camera aiming at center between two game objects

Good evening everyone,

In my game prototype, I have two game objects the player can control with joysticks. Nom imagine a line that links those game objects. I want to make a camera which is aiming dynamically the center of this line.

I attached the script below to my new camera and I thought it would work, but I have the following error:

“Assets/Script/SwitchCamera.cs(13,25): error CS0029: Cannot implicitly convert type UnityEngine.Vector3' to UnityEngine.Transform’” (it’s refering to the line “center = ((Capsule1.position[…])” ).

I’m new to unity and C# and made research on how Transform.LookAt / Vector3 / Transform.position worked, but I don’t really understand my error and where I’m wrong.

using UnityEngine;
using System.Collections;

public class SwitchCamera : MonoBehaviour {

	public Transform Capsule1;
	public Transform Capsule2;
	public Transform center;
	
	void Update () {
			center = ((Capsule1.position + Capsule2.position)/2);
			transform.LookAt(center);
		}
}

OR maybe is it better to use this code as a base:

using UnityEngine;
using System.Collections;

    public class SwitchCamera : MonoBehaviour {
    
    	public Transform Capsule1;
    	public Transform Capsule2;
    	public Transform center;
    	
    	void Update () {
    		if(Capsule1){
    			float dist = Vector3.Distance(Capsule1.position, Capsule2.position);	
    			print("Distance to other: " + dist);
    		}
    	}
    }

and then calculate the center of “dist”, then make the camera aim this center ?

Does anyone have hints or advices ?

Thanks a lot !

I was going to suggest the Vector3.Distance… however, I’ve read where people say it takes a little bit more of a toll on your cpu, versus measuring the difference between all three axis yourself. I would suggest that you do something like procedurely find the difference between object1’s x and object2’s x, y’s and z’s. Then, from either object’s position, add/subtract the 1/2 of the difference and rotate your camera to face that point.

Hope this helps!

Your error was because center should have been declared a Vector3. I’d do my calcs this way:

using UnityEngine;
using System.Collections;
 
public class SwitchCamera : MonoBehaviour {
 
    public Transform Capsule1;
    public Transform Capsule2;
    public Vector3 center;
 
    void Update () {
         center = ((Capsule2.position - Capsule1.position)/2.0f) + Capsule1.position;
         transform.LookAt(center);
       }
}