自学笔记 仅供参考
简单脚本编写流程:(控制物体移动)
1.在任意3D Object中Add Component添加 脚本Scripts 取名PlayerInput 如下图
PlayerInput -> 负责处理用户输入 再传导到 PlayerController
using System.Collections; //编辑器自带的头文件补充
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour // 继承MonoBehaviour
{
[SerializeField] //使变量在 unit 里可调
private float speed = 5f; //可调节的速度
[SerializeField]
private float lookSensitivity = 8f;
[SerializeField]
private PlayerController controller;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked; //隐藏鼠标 锁定鼠标
}
// Update is called once per frame
void Update()
{
float xMov = Input.GetAxisRaw("Horizontal"); //Horizontal 获取用户输入横向移动的 api
float yMov = Input.GetAxisRaw("Vertical"); //Vertical 获取用户输入纵向移动的 api
Vector3 velocity = (transform.right * xMov + transform.forward * yMov).normalized * speed;
// Vector3 3D 向量 transform.right transform.forward :向量 normalized 标准化
controller.Move(velocity); //调用 PlayerController 移动函数
float xMouse = Input.GetAxisRaw("Mouse X"); //GetAxisRaw 输入的原值 GetAxis 较为平滑
float yMouse = Input.GetAxisRaw("Mouse Y");
Vector3 yRotation = new Vector3(0f, xMouse, 0f) * lookSensitivity;
Vector3 xRotation = new Vector3(-yMouse, 0f, 0f) * lookSensitivity;
controller.Rotate(yRotation, xRotation);
}
}
2. 同时创建PlayerContorller 处理组件的控制
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private Rigidbody rb; // 获取需要移动的物体信息
[SerializeField]
private Camera cam;
private Vector3 velocity = Vector3.zero; // 速度向量 每秒移动的速度
private Vector3 yRotation = Vector3.zero; // 旋转角色
private Vector3 xRotation = Vector3.zero; // 旋转视角
public void Move(Vector3 _velocity)
{
velocity = _velocity;
}
public void Rotate(Vector3 _yRotation, Vector3 _xRotation)
{
yRotation = _yRotation;
xRotation = _xRotation;
}
private void PerformMovement()
{
if(velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime); // rb.position 物体选择的位置(向量) 速度*FixedUpdate deltatime
}
}
private void PerformRotation()
{
if(yRotation != Vector3.zero)
{
rb.transform.Rotate(yRotation);
}
if(xRotation != Vector3.zero)
{
cam.transform.Rotate(xRotation);
}
}
private void FixedUpdate() // 相邻两次执行时间间隔 相同 rigidbody 都要用FixedUpdate
{
PerformMovement();
PerformRotation();
}
}
用户控制 与 用户输入分开的 好处:
便于后续更改 以及 模块化处理代码
day 1 中遇到的 问题汇总
1.Unity中的MonoBehaviour是什么?
参见文章:Unity中的MonoBehaviour
通俗来讲就是几乎每个脚本继承的类;不然无法在GameObject里以组件的方式添加进Inspector
2.FixUpdate 、Update、start、lateUpdate 是什么?
- FixedUpdate:每帧调用而且每帧的时间间隔是固定的。刚体的运动都需要用FixedUpdate。
- Update:每帧调用但是每帧的时间间隔不固定,与电脑性能有关。较为灵活。每次调用时间不同,如果处理运动,就会照成位置的偏移。
- LateUpdate:与update相同,但再所有update处理完后 调用。
- start: 在所有之前调用。仅调用一次。