unity中C#文件创建与介绍
创建C#文件的位置在界面的最下面Assets处,创建方法是在下面:
创建好的界面如下所示:
创建完C#后双击即可打开,打开后界面如下:
第一个函数void Start()是只有在代码开始的时候运行一次,不再更新;后面的函数void Update()是在运行过程中每一秒更新一次。
创建人物三维移动
如果想要让我们创建的人物移动,就要通过添加C#插件进行控制,代码如下:
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class playermove : MonoBehaviour
{
public float speed;
public CharacterController playercontroller;
// Update is called once per frame
void Update()
{
float x, z;
x = Input.GetAxis("Horizontal");//获取水平状态
z = Input.GetAxis("Vertical"); //获取垂直状态
Vector3 move;//创建三维向量(x,y,z)
move = transform.right * x + transform.forward * z;
playercontroller.Move(move * speed * Time.deltaTime);
}
}
创建完成后我们就要将将其添加到创建的物体上:点击创建的人物后再点击右侧的“添加组件”,输入我们创建的C#文件名。
创建视野跟随
如果我们想要创建第一人称视角的游戏,就要放一个摄像头在创建的人物上,并跟随人物移动:
代码如下:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using UnityEngine;
public class camerlook : MonoBehaviour
{
public float MouseSpeed;
public Transform player;
private float xmove;
// Start is called before the first frame update
void Start()
{
//锁定鼠标位置,防止乱跑而造成奇怪的视角
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
//创建鼠标(摄像机)移动
float x, y;
//X上的位移等于鼠标X移动速度乘时间
x = Input.GetAxis("Mouse X") * MouseSpeed * Time.deltaTime;
y = Input.GetAxis("Mouse Y") * MouseSpeed * Time.deltaTime;
xmove = xmove - y;
//对x方向移动进行限幅,感兴趣可以试试注释掉是什么现象(斜眼笑)
xmove = Mathf.Clamp(xmove, -90, 90);
this.transform.localRotation = Quaternion.Euler(xmove, 0, 0);
//创建三维向量
player.Rotate(Vector3.up * x);
}
}