Camera glitch or a mistake?

Hi guys,

I made a very simple test case of something I am encountering.

There is a cube that moves ( just in z space for now) and the cube is followed by a sphere on a certain distance.
My camera will follow the sphere, also on a certain distance.

The thing is that it glitches a lot! I simplified the code and the setup of the scene and it still persists.
Can anyone point out my mistake here? The project is attached!

Thx for looking into this.

693463–24952–$Glitch.zip (157 KB)

693651–24960–$Glitch.zip (167 KB)
hey,
I use unity script to solve your problem you can translate it to c# its your wish. Just study my script you can understand what mistake you are doing.

to move cube i use these set of codes

var speed = 10;
function Update () 
{
	transform.Translate(0,0,speed*Time.deltaTime);
}

and to follow cube

var targetcube :Transform;
var speed = 10;
function Update () 
{	
	var distance = Vector3.Distance(targetcube.transform.position,transform.position);
	if(distance > 3)
	{
		var delta = targetcube.transform.position - transform.position;
		delta.Normalize();
		
		var moveSpeed = speed * Time.deltaTime;
      
		transform.position = transform.position + (delta * moveSpeed);
		
		transform.LookAt(targetcube);
	}
}

Hi sushanta,

Thanks for your solution, that seems to work better. Although, I can’t see why I am not able to just set the position a certain distance behind another object like this:

 transform.position = followTarget.position - Vector3.forward * distance;

What is wrong with that code?

Okay I found something really interesting.

Because the FOLLOW script was both on the camera (camera follows sphere) and the sphere (sphere follows the cube) , it had problems with the execution order.

I “fixed” this by creating a new class for the camera behavior (exact same code as the follow behavior), and changed the execution order like this:

-100 JustMove
-50 JustFollow
-20 CameraFollow

It seems wrong that I need a duplicate of my follow behavior for the camera. Can anyone shine a light on this one?