gpt4 book ai didi

c# - Unity3D C#。使用 transform.RotateAround() 函数同时保持两个对象之间的距离不变

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:49 24 4
gpt4 key购买 nike

我正在尝试练习在 Unity 3D 中制作第三人称 Controller 。我是初学者,对如何使我的 Controller 发挥作用完全感到困惑。我一直在做数小时的研究,但我找不到任何线索似乎可以回答我的问题。我有两个脚本,一个 CameraController 和一个 CharacterController。我的代码如下。

相机 Controller :

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
public GameObject target;
public float rotationSpeed;
Vector3 offset;
Vector3 CameraDestination;


// Use this for initialization
void Start () {
offset = transform.position - target.transform.position;
CameraDestination = offset + transform.position;
rotationSpeed = 50f;
transform.position = CameraDestination;
}

// Update is called once per frame
void Update () {

transform.LookAt (target.transform.position);
float h = Input.GetAxisRaw ("Horizontal");
transform.RotateAround (target.transform.position, Vector3.up, Time.deltaTime * h * rotationSpeed);

target.transform.Rotate (0f, Time.deltaTime * h * rotationSpeed, 0f);

}
}

角色 Controller :

using UnityEngine;
using System.Collections;

public class CharController : MonoBehaviour {

public float playerSpeed = 10f;


// Use this for initialization
void Start () {



}

// Update is called once per frame
void Update () {
float Vertical = Input.GetAxis("Vertical");
transform.position += transform.forward * Time.deltaTime * playerSpeed * Vertical;



}
}

当按下左箭头键或右箭头键时,播放器和相机都会旋转。如果我小时候尝试将相机连接到播放器,相机的旋转就会变得困惑,但如果我不将相机连接到播放器,相机就会停止跟随播放器。如果我尝试将相机设置到相对于玩家的特定位置,它会停止像预期的那样围绕玩家旋转。我实在想不出一个可行的方法。感谢您提前回答我的问题!

最佳答案

当我开始做这件事时,我喜欢有一个空的游戏对象,它有 2 个 child ,相机,然后是角色的网格。

> CharacterController
> Camera
> CharacterRig

当你想旋转角色时,旋转 CharacterController,然后当你想围绕角色旋转相机时,将代码更改为:

transform.RotateAround (CharacterRig.transform.position, Vector3.up, Time.deltaTime * h * rotationSpeed);

这将允许您的相机旋转而不管任何角色动画,应该可以解决您的问题。如果您想稍后实现动画,这一点非常重要,因为您不希望将相机作为动画对象的父级,因为它会随着动画移动。

附言您的代码看起来很好。当然,这纯粹是您设置游戏对象的方式。

关于c# - Unity3D C#。使用 transform.RotateAround() 函数同时保持两个对象之间的距离不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167799/

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