- Home /
Question by
Hertex · Sep 18, 2017 at 10:00 PM ·
c#3rd person camerarotate-around
Third Person camera, how to rotate around character?
I have created this script, my camera look to character and follow him, but cannot rotate around him.
here my script:
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
Best Answer
Answer by tormentoarmagedoom · Sep 19, 2017 at 07:53 AM
Good day @Hertex !
Look at this post, and this code. You need to reate an "offset", a "pivot" to do it.
public class Orbit : MonoBehaviour {
public float turnSpeed = 4.0f;
public Transform player;
private Vector3 offset;
void Start () {
offset = new Vector3(player.position.x, player.position.y + 8.0f, player.position.z + 7.0f);
}
void LateUpdate()
{
offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
transform.position = player.position + offset;
transform.LookAt(player.position);
}
}
If helped, mark the answer as good please
Bye :D