camera problem,please help me camera problem

I use this code to follow player without rotation
transform.position = new Vector3 (targetx.position.x, targetx.position.y + 3, targetx.position.z - 5);
targetx is the player
but when player turn to opposite direction camera become in front of player I want camera always behind the player but by similar code without flekring
thank you very much

Hi,

There is two different ways to do this that equate to the same thing.

The first way is to simply drag and drop the camera in the editor view and it will follow the player from the same position.

The second way is a modification of your script. Your postitions are in world coordinates ie targetx.position.x is the x position in the worlds grid system this will not change when the object changes rotation or move.

You can use the following to get the affect you want

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {

    //Create a Global position that will become relative to the objects center point
    Vector3 CamPos = new Vector3(0,3,-5);
    
    //We use LateUpdate as it runs after the Update function
    //and will remove any jitter
    void LateUpdate()
    {
        //We use the function InverseTransformPoint() to make our Vector3
        //relative to our target objects position
        transform.position = targetx.InverseTransformPoint(CamPos);

        //Now we need to rotate the camera face the same direction as the object
        transform.rotation = targetx.rotation;
    }
}