如何让相机跟随 unity3d C# 中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10752435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:07:07  来源:igfitidea点击:

How do I make a camera follow an object in unity3d C#?

c#objectcameraunity3d

提问by chesnutcase

I have an object called Ball, and I added keyboard interactivity to it(WASD to move the ball) I need the camera to stay behind and follow the ball, but I am getting errors.

我有一个名为 Ball 的对象,我向它添加了键盘交互性(WASD 以移动球)我需要相机留在后面并跟随球,但是我遇到了错误。

using UnityEngine;
using System.Collections;
public class ballmain : MonoBehaviour {
    public bool isMoving = false;
    public string direction;
    public float camX;
    public float camY;
    public float camZ;
    // Use this for initialization
    void Start () {
        Debug.Log("Can this run!!!");
    }

    // Update is called once per frame
    void Update () {
        camX = rigidbody.transform.position.x -=10;
        camY = rigidbody.transform.position.y -=10;
        camZ = rigidbody.transform.position.z;
        camera.transform.position = new Vector3(camX, camY, camZ);
            //followed by code that makes ball move
    }
}

I get error "Assets/ballmain.cs(18,44): error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable" Does anyone know the answer? If I comment out the code about the camera the ball can move around.

我收到错误“Assets/ballmain.cs(18,44): error CS1612: 无法修改‘UnityEngine.Transform.position’的值类型返回值。考虑将值存储在临时变量中”有人知道答案吗?如果我注释掉有关相机的代码,球可以四处移动。

回答by Skizz

The -=in these lines:

-=这些线路:

   camX = rigidbody.transform.position.x -=10;
   camY = rigidbody.transform.position.y -=10;

is wrong. The -=will attempt to modify the rigidbody.transform.position. You just want -.

是错的。该-=会尝试修改rigidbody.transform.position。你只想要-.

However, as it stands, the camera won't track changes in the target's Z position, nor will it track properly if the camera is rotated. To get the correct position you need (in vectors):-

但是,就目前而言,相机不会跟踪目标 Z 位置的变化,也不会在相机旋转时正确跟踪。要获得您需要的正确位置(在向量中):-

cam_pos = target_pos - dist_to_target * cam_look_at

回答by Skizz

here you go . a full code.

干得好 。一个完整的代码。

Simple Following

简单跟随

using UnityEngine;
using System.Collections;

public class Follow: MonoBehaviour {
public Transform target;
public float smooth= 5.0f;
void  Update (){
    transform.position = Vector3.Lerp (
        transform.position, target.position,
        Time.deltaTime * smooth);
} 

    } 

Advanced Following

高级关注

using UnityEngine;
using System.Collections;

public class SmoothFollowScript: MonoBehaviour {

// The target we are following
public  Transform target;
// The distance in the x-z plane to the target
public int distance = 10.0;
// the height we want the camera to be above the target
public int height = 10.0;
// How much we 
public heightDamping = 2.0;
public rotationDamping = 0.6;


void  LateUpdate (){
    // Early out if we don't have a target
    if (TargetScript.russ == true){
    if (!target)
        return;

    // Calculate the current rotation angles
    wantedRotationAngle = target.eulerAngles.y;
    wantedHeight = target.position.y + height;

    currentRotationAngle = transform.eulerAngles.y;
    currentHeight = transform.position.y;

    // Damp the rotation around the y-axis
    currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

    // Damp the height
    currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);

    // Convert the angle into a rotation
    currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);

    // Set the position of the camera on the x-z plane to:
    // distance meters behind the target
    transform.position = target.position;
    transform.position -= currentRotation * Vector3.forward * distance;

    // Set the height of the camera
    transform.position.y = currentHeight;

    // Always look at the target
    transform.LookAt (target);
}
}
}

回答by Reaz Murshed

Include Standard Mobile Asset to your project. It contains a SmoothFollow2D.js code in its script section. Attach this code with the gameobject and initialize public variables. This will simply do the job for you.

将标准移动资产包含到您的项目中。它的脚本部分包含一个 SmoothFollow2D.js 代码。将此代码与游戏对象附加并初始化公共变量。这只会为您完成工作。

回答by Sourav Kondapaka

If you just simply want to follow the target object align the position of the camera the way you want it and make the camera the child of the target object and the rest will do

如果您只是想跟随目标对象,请按照您想要的方式对齐相机的位置并使相机成为目标对象的子对象,其余的就可以了

回答by NabeelSaleem

I found this simple and useful unity 2d camera follow script.

我发现这个简单而有用的统一二维相机跟随脚本。

using UnityEngine;
using System.Collections;

public class FollowCamera : MonoBehaviour {

public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
// Use this for initialization
void Start () {
    targetPos = transform.position;
}

// Update is called once per frame
void FixedUpdate () {
    if (target)
    {
        Vector3 posNoZ = transform.position;
        posNoZ.z = target.transform.position.z;

        Vector3 targetDirection = (target.transform.position - posNoZ);

        interpVelocity = targetDirection.magnitude * 5f;

        targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime); 

        transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);

    }
   }
}

source unity2d camera follow script

unity2d 相机跟随脚本

回答by Dilmer

Here're one script I found useful during my game development. I didn't create them so I give credit to wiki.unity3d.com for providing this amazing script.

这是我在游戏开发过程中发现有用的一个脚本。我没有创建它们,所以我感谢 wiki.unity3d.com 提供了这个惊人的脚本。

Smooth Follow:

平滑跟随:

using UnityEngine;
using System.Collections;

        public class SmoothFollow2 : MonoBehaviour {
        public Transform target;
        public float distance = 3.0f;
        public float height = 3.0f;
        public float damping = 5.0f;
        public bool smoothRotation = true;
        public bool followBehind = true;
        public float rotationDamping = 10.0f;

        void Update () {
               Vector3 wantedPosition;
               if(followBehind)
                       wantedPosition = target.TransformPoint(0, height, -distance);
               else
                       wantedPosition = target.TransformPoint(0, height, distance);

               transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);

               if (smoothRotation) {
                       Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
                       transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
               }
               else transform.LookAt (target, target.up);
         }
}

More information about my work

关于我的工作的更多信息