gpt4 book ai didi

c# - 使用 Unity3D 相机平滑跟随 2D 从 UnityScript 到 C#

转载 作者:行者123 更新时间:2023-12-02 21:51:50 25 4
gpt4 key购买 nike

我正在制作一个脚本,用于 Unity3D 的主相机对象,以便相机跟随 2D 平台游戏世界中的角色。

我尝试将其从 UnityScript 脚本转换为 C#,在第 26 行中收到错误:“无法修改‘UnityEngine.Transform.position’的值类型返回值。请考虑将该值存储在临时变量中。 ”

原始 UnityScript 版本

var cameraTarget : GameObject;
var player : GameObject;

var smoothTime : float = 0,1;
var cameraFollowX : boolean = true;
var cameraFollowY : boolean = true;
var cameraFollowHeight : boolean = false;
var cameraHeight : float = 2.5;
var velocity : Vector2;
private var thisTransform : Transform;

function Start ()
{
thisTransform = transform;
}

function Update ()
{

if (cameraFollowX)
{
thisTransform.position.x = Mathf.SmoothDamp (thisTransform.position.x, cameraTarget.transform.position.x, velocity.x, smoothTime);
}

if (cameraFollowY)
{
thisTransform.position.y = Mathf.SmoothDamp (thisTransform.position.y, cameraTarget.transform.position.y, velocity.y, smoothTime);
}

if (!cameraFollowX & cameraFollowHeight)
{
camera.transform.position.y = cameraHeight;
}

}

我的 C# 版本

using UnityEngine;
using System.Collections;

public class CameraSmoothFollow : MonoBehaviour {

public GameObject cameraTarget; // object to look at or follow
public GameObject player; // player object for moving

public float smoothTime = 0.1f; // time for dampen
public bool cameraFollowX = true; // camera follows on horizontal
public bool cameraFollowY = true; // camera follows on vertical
public bool cameraFollowHeight = true; // camera follow CameraTarget object height
public float cameraHeight = 2.5f; // height of camera adjustable
public Vector2 velocity; // speed of camera movement

private Transform thisTransform; // camera Transform

// Use this for initialization
void Start () {
thisTransform = transform;
}

// Update is called once per frame
void Update () {
if (cameraFollowX){
thisTransform.position.x = Mathf.SmoothDamp (thisTransform.position.x, cameraTarget.transform.position.x, ref velocity.x, smoothTime); // Here i get the error
}
if (cameraFollowY) {
// to do
}
if (!cameraFollowX & cameraFollowHeight) {
// to do
}
}
}

任何帮助将不胜感激。

最佳答案

发生此错误的原因是 Transform.position 是值类型(可能是 struct)。这意味着当您访问 position 的 X 属性时,您访问的是副本而不是真实的东西。要分配给位置属性,您需要创建一个新的 Vector3 并将其分配给位置属性。您的代码将如下所示:

thisTransform.position = new Vector3 (Mathf.SmoothDamp (thisTransform.position.x, cameraTarget.transform.position.x, ref velocity.x, smoothTime), thisTransform.position.y, thisTransform.position.z);

或者也许更干净:

float tempX = new Vector3 (Mathf.SmoothDamp (thisTransform.position.x, cameraTarget.transform.position.x, ref velocity.x, smoothTime);
thisTransform.position = new Vector3 (tempX, thisTransform.position.y, thisTransform.position.z);

关于c# - 使用 Unity3D 相机平滑跟随 2D 从 UnityScript 到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18477411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com