我有一个名为 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):错误CS1612:无法修改'UnityEngine.Transform.position'的值类型返回值。请考虑将值存储在临时变量中”
有人知道答案吗?如果我注释掉有关相机的代码,球可以四处移动。

最佳答案

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

简单跟随

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

关于c# - 如何让相机跟随 unity3d C# 中的对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10752435/

10-12 00:39