Question by
Hertex · Sep 18, 2017 at 09:49 PM ·
c#3rd person controller
Can someone help me with my third person camera?
I want to create a good third person camera but i have some trouble: my camera can only follow my character and look at him, but cannot rotate around him.
here is my code:
Vector3 offset = Vector3.zero;
Vector3 velocity = Vector3.zero;
public float distance = 10f;
float currentDistance;
float minDistance = 16f;
float maxDistance = 20f;
public float height = 8f;
public float targetHeadHeight = 7f;
float smooth = 0.3f;
public Transform target; //for read target position
void Awake(){
offset = new Vector3 (target.position.x, (target.position.y + height), (target.position.z - distance));
transform.position = offset;
}
void Update(){
LookAtTarget ();
}
void LateUpdate(){
UpdatePosition ();
}
void LookAtTarget(){
Vector3 relativePos = target.position - transform.position;
Vector3 y = new Vector3 (0, targetHeadHeight, 0);
Quaternion newRotation = Quaternion.LookRotation (relativePos + y);
transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, 10f * Time.deltaTime);
}
void UpdatePosition(){
currentDistance = Vector3.Distance (transform.position, target.position);
if (currentDistance < minDistance) {
currentDistance = minDistance;
} else if (currentDistance > maxDistance) {
currentDistance = maxDistance;
}
distance = currentDistance;
offset = new Vector3 (target.position.x, (target.position.y + height), (target.position.z - distance));
transform.position = Vector3.SmoothDamp (transform.position, offset, ref velocity , smooth);
}
Comment
Your answer
Follow this Question
Related Questions
How to make an object move in the direction another object is facing on 2 axis? 1 Answer
How to fix "the type or namespace ".." could not be found" in unity 0 Answers
Destroy GameObject inconsistent with Instantiated children 1 Answer
Adding a unique element from one list to another list 2 Answers
ienumerator stops at yield return new waitforseconds() 1 Answer