C# Unity中第一人称控制器代码引起的问题
我正在创建一个统一的第一人称控制器。非常基本的东西,相机是玩家胶囊的孩子。代码起作用,但我需要帮助解释发生了什么 *摄影机是层次结构中玩家的子级 以下是我的问题:C# Unity中第一人称控制器代码引起的问题,c#,unity3d,C#,Unity3d,我正在创建一个统一的第一人称控制器。非常基本的东西,相机是玩家胶囊的孩子。代码起作用,但我需要帮助解释发生了什么 *摄影机是层次结构中玩家的子级 以下是我的问题: 在PlayerMovement中,当Unity在Y轴上时,为什么我们要在Z轴上平移以实现垂直运动 在CamRotation中,我不知道Update()中发生了什么。为什么我们要将水平运动应用于玩家,而将垂直运动应用于相机?为什么它不应用于同一个游戏对象 mouseMove想要实现什么?我们为什么使用var 我想我们得到了一个鼠标移
Update()
中发生了什么。为什么我们要将水平运动应用于玩家,而将垂直运动应用于相机?为什么它不应用于同一个游戏对象mouseMove
的不同组件(字符的.x
和相机的.y
)。这意味着来自角色的移动不等于来自摄影机的移动;一个应该比另一个快/慢
var
是一个预定义的C#关键字,它让编译器找出合适的类型。在本例中,它与您在vector2mousemove=newvector2(…)中编写的Vector2
相同代码>
mouseMove
中的值。就这样.x
应用于角色,因为在代码行后注释时,您希望将其水平移动。对于相机,应用了.y
,因为您希望垂直移动它。
负值可能是因为轴是反转的,所以将其设置为负值,以便相机能够自然移动。这与某些游戏的设置原理相同,它们允许您反转Y轴。非常感谢。我现在更明白了@krobelusmeetsyndra你能不能也向我解释一下CamRotation,为什么我们对角色应用y轴旋转,而对相机应用x轴旋转?我的意思是:character.transform.Rotate(0,mouseMove.x,0);transform.Rotate(-mouseMove.y,0,0);还有,为什么我们想要负值?(-mouseMove.y)哇,很抱歉,这条评论看起来太乱了,我不知道如何更好地格式化。我已经编辑了我的答案,因此它也涵盖了您在评论中提出的问题。如果我的问题适合你,请接受它
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed = 5.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float mvX = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
float mvZ = Input.GetAxis("Vertical") * Time.deltaTime * speed;
transform.Translate(mvX, 0, mvZ);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamRotation : MonoBehaviour {
public float horizontal_speed = 3.0F;
public float vertical_speed = 2.0F;
GameObject character; // refers to the parent object the camera is attached to (our Player capsule)
// initialization
void Start()
{
character = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
var mouseMove = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
mouseMove = Vector2.Scale(mouseMove, new Vector2(horizontal_speed, vertical_speed));
character.transform.Rotate(0, mouseMove.x, 0); // to rotate our character horizontally
transform.Rotate(-mouseMove.y, 0, 0); // to rotate the camera vertically
}
}