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

Posted

技术标签:

【中文标题】如何使相机跟随unity3d C#中的对象?【英文标题】:How do I make a camera follow an object in unity3d C#? 【发布时间】:2012-05-25 10:06:31 【问题描述】:

我有一个名为 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
    

我收到错误“Assets/ballmain.cs(18,44): error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'。考虑将值存储在临时变量中” 有人知道答案吗?如果我注释掉有关相机的代码,球可以四处移动。

【问题讨论】:

【参考方案1】:

给你。完整的代码。

简单跟随

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);
 

     

高级关注

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);



【讨论】:

每次我尝试这个,Unity 都会冻结。为什么?它什么也没做,我必须终止这个过程。 不知道。我从来没有遇到过这个问题。您希望以何种方式关注您的对象? 不确定它出了什么问题,但是在重新安装 Unity 后它可以工作 :) 它也可以在我的笔记本电脑上工作,我的桌面安装有问题。【参考方案2】:

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

【讨论】:

【参考方案3】:

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

流畅跟随:

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

【讨论】:

我一直在寻找可以附加到相机而不是目标的脚本,并且实际上跟随在播放器后面。非常感谢。【参考方案4】:

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

【讨论】:

【参考方案5】:

我发现了这个简单实用的统一 2d 相机跟随脚本。

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);

    
   

来源unity2d camera follow script

【讨论】:

【参考方案6】:

这些行中的-=

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

错了。 -= 将尝试修改 rigidbody.transform.position。你只想要-

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

cam_pos = target_pos - dist_to_target * cam_look_at

【讨论】:

所以它的 camera.transform.position = 刚体.transform.position - 10 *cam_look_at?什么是 cam_look_at? @chesnutcase:相机的位置和方向存储为 4x4 矩阵。矩阵的行(或列,取决于它的设置方式)等于:单位右向量、单位上向量、向量处的单位、位置。 right、up 和 at 向量是相机认为正确的方向,在世界坐标中向上和向前,forward/at 是相机正在看的方向。这三个向量是正交的(即任意两个的点积为零)。

以上是关于如何使相机跟随unity3d C#中的对象?的主要内容,如果未能解决你的问题,请参考以下文章

Unity3d学习 相机的跟随

Unity3d学习 相机的跟随

unity3d相机怎么跟随鼠标移动

Unity3D 利用FSM设计相机跟随实现

在OpenGL中使对象跟随相机

怎么用unity3d模拟吃鸡中的摄像机跟随