简体   繁体   中英

Rotate camera around object, ease on change position

This question seems rather popular, but none of my searches appear to solve my issue.

I have a tower, which is building itself block by block. I want to have a camera, circling around the currently building block, and when the next block is about to be placed, translate the camera vertically, or in whatever direction needed, so the center of the rotation (in 3D space) is always that cube.

I have currently this code, but after few blocks, it does not keep it's current angle of view and the movement is just a big jump. Note that the position changes by 1 in any direction.

Here is the code:

transform.position = targetPosition + (transform.position - targetPosition).normalized * orbitDistance;
transform.RotateAround(targetPosition, Vector3.up, orbitSpeed * Time.deltaTime);

what am I doing wrong?

I would use a camera boom technique here.

First, have a gameobject that represents the camera's "focus point", the point that the camera is always facing and rotating around. Call it Focus Point . Then, have a child of Focus Point that will hold the camera component. Call it Camera . They would have this relationship.:

├──Focus Point
│   └── Camera

The Camera gameobject should be rotated and positioned so that it is facing the position of Focus Point . This shouldn't needed to be done in code, since all you're doing will be changing the rotation and position of Focus Point to adjust the camera. A script like this could be attached to Focus Point :

public class FocusPointScript : MonoBehaviour 
{ 
    public Vector3 targetPosition;
    public float translateSpeed = 0.1f;
    public float rotateSpeed = 10f;

    void Start()
    {
        targetPosition = transform.position;
    }
  
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, 
                translateSpeed * Time.deltaTime);
        transform.Rotate(0f, rotateSpeed * Time.deltaTime, 0f);
    }
}

And if you want to adjust how far the camera is from the focus point, you can change the position of Camera forward or backward or (I would not do both) change the localScale of Focus Point :

float moveDelta = 0f; 
// calculate how to adjust
cameraGameObject.transform.Translate(moveDelta * Vector3.forward);

or

float scaleFactor = 1f; 
// calculate how to adjust
focusPointGameObject.transform.localScale = 
        scaleFactor * focusPointGameObject.transform.localScale;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM