------------------------------ 代码例子 ------------------------------------
//----计算两个向量夹角
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//Vector3可以带吧: 向量,坐标,旋转,缩放, 为什么是3,就是3个参数3维的意,有4,有2
Vector3 v = new Vector3(1, 1, 0.5f);
v = Vector3.zero;
v = Vector3.right;
Vector3 v2 = Vector3.forward;
//计算两个向量夹角
Debug.Log(Vector3.Angle(v, v2));//计算两点之间的距离
Debug.Log(Vector3.Distance(v, v2));//点乘
Debug.Log(Vector3.Dot(v, v2));//叉乘
Debug.Log(Vector3.Cross(v, v2));//插值
Debug.Log(Vector3.Lerp(Vector3.zero, Vector3.one, 0.8f));//向量的模
Debug.Log(v.magnitude);//规范化向量
Debug.Log(v.normalized);
}
// Update is called once per frame
void Update()
{
}
}
//----欧拉角 转 四元数, 四元数 转 欧拉角
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test2 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("-----------------运行Test2.cs-------------");
//旋转: 欧拉角,四元数
Vector3 rotate = new Vector3(0, 30, 0);
Quaternion quaternion = Quaternion.identity;//欧拉角转为四元数
quaternion = Quaternion.Euler(rotate);
//四元数转为欧拉角
rotate = quaternion.eulerAngles;//看向一个物体
quaternion = Quaternion.LookRotation(new Vector3(0, 0, 0));
}
// Update is called once per frame
void Update()
{
}
}
//----画线
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test3 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("test");
Debug.LogWarning("test2");
Debug.LogError("test3");
}
// Update is called once per frame
void Update()
{
////绘制一条线 起点,终点
//Debug.DrawLine(new Vector3(1, 0, 0), new Vector3(1, 1, 0), Color.blue);
////绘制一条射线 起点,射线
//Debug.DrawRay(new Vector3(1, 0, 0), new Vector3(1, 1, 0), Color.red);
//绘制一条线 起点,终点
Debug.DrawLine(Vector3.zero, Vector3.one, Color.blue);
//绘制一条射线 起点,射线,颜色
Debug.DrawRay(Vector3.zero, Vector3.up, Color.yellow);
}
}
//----获取游戏对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test4 : MonoBehaviour
{
//定义立方体 - 这样就可以在面格把物体拖进来 Cube自动翻译为:立方体
public GameObject Cube;
//定义预设体 - 这样就可以在面格把物体拖进来 Prefab自动翻译为:预设体
public GameObject Prefab;
public GameObject Name; //Name自动翻译为:名称
// Start is called before the first frame update
void Start()
{
////拿到当前脚本所挂载的游戏物体
//GameObject go = this.gameObject;
//Debug.Log(go.name);
//名称
Debug.Log(gameObject.name);
//tag
Debug.Log(gameObject.tag);
//layer
Debug.Log(gameObject.layer);
//立方体的名称
Debug.Log(Cube.name);
//当前真正的激活状态
Debug.Log(Cube.activeInHierarchy);
//当前自身激活状态
Debug.Log(Cube.activeSelf);
//获取Transform组件
Transform trans = this.transform;
Debug.Log(transform.position);
//获取其他组件 除了Transform以后的
BoxCollider bc = GetComponent<BoxCollider>();
//MeshRenderer aa = GetComponent<MeshRenderer>();
////获取当前物体的子物体身上的某个组件
//GetComponentInChildren<CapsuleCollider>(bc);
////获取当前物体的父物体身上的某个组件
//GetComponentInParent<BoxCollider>();
//添加一个组件
gameObject.AddComponent<AudioSource>();
//通过游戏物体的名称来获取游戏物体
GameObject test = GameObject.Find("Test");
Debug.Log(test.name);
//通过游戏标签来获取游戏物体
test = GameObject.FindWithTag("Enemy");
test.SetActive(false);
Debug.Log(test.name);
//通过预设体来实例化一个游戏物体
GameObject go = Instantiate(Prefab,Vector3.zero,Quaternion.identity);
//销毁
//Destroy(go);
}
// Update is called once per frame
void Update()
{
}
}
//----时间
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test5 : MonoBehaviour
{
float timer = 0;
// Start is called before the first frame update
void Start()
{
//游戏开始到现在所花的时间
Debug.Log(Time.time);
//时间缩放值
Debug.Log(Time.timeScale);
//固定时间间隔
//Debug.Log(Time.fixedDeltaTime):
Debug.Log(Time.fixedDeltaTime);
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
//上一帧到这一帧所用的游戏时间
Debug.Log(Time.deltaTime);
//如果大于10秒
if (timer > 10){
Debug.Log("大于10秒了");
}
}
}
//----文件存储
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test6 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//游戏数据文件夹路径(只读,加密压缩) D:/Program Files/Unity/job/5/Assets
Debug.Log(Application.dataPath);
//持久化文件夹路径 c:/Users/Administrator/AppData/LocalLow/DefaultCompany/5
Debug.Log(Application.persistentDataPath);
//StreamingAssets文件夹路径(只读,配置文件) D:/Program Files/Unity/job/5/Assets/StreamingAssets
Debug.Log(Application.streamingAssetsPath);
//临时文件夹 C:/Users/Administrator/AppData/Local/Temp/Defaultcompany/5
Debug.Log(Application.temporaryCachePath);
//控制是否在后台运行 True //文件->生成设置->玩家设置->默认(设置 Windows, Mac, Linux)->分辨率和演示->后台运行 打勾即可
Debug.Log(Application.runInBackground);
////打开url
//Application.OpenURL("https://space.bilibili.com/67744423");
////退出游戏
//Application.Quit();
}
// Update is called once per frame
void Update()
{
}
}
//----加载场景
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Test7 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//两个类,场景类,场景管理类
////场景跳转
//SceneManager.LoadScene("Scenes2");
//获取当前场景
Scene scene = SceneManager.GetActiveScene();
//场景名称
Debug.Log(scene.name);
//场景是否已经加载
Debug.Log(scene.isLoaded);
//场景路径
Debug.Log(scene.path);
//场景索引
Debug.Log(scene.buildIndex);
//所有的游戏物体
GameObject[] gos = scene.GetRootGameObjects();
Debug.Log("总共有 " + gos.Length + " 个根游戏物体");
foreach (GameObject go in gos)
{
Debug.Log(go.name);
}
//场景管理类
//创建新场景
Scene newScene = SceneManager.CreateScene("newScene");
//已加载场景个数
Debug.Log(SceneManager.sceneCount);
////卸载场景
//SceneManager.UnloadSceneAsync(newScene);
//加载场景
SceneManager.LoadScene("Scenes2", LoadSceneMode.Additive); //LoadSceneMode.Additive 添加 , LoadSceneMode.Single 为替换
}
// Update is called once per frame
void Update()
{
}
}
//----异步加载场景
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Test7777 : MonoBehaviour
{
AsyncOperation operation;
// Start is called before the first frame update
void Start()
{
StartCoroutine(loadScene());
}
//协程方法用来异步加载场景1个引用
IEnumerator loadScene() {
operation = SceneManager.LoadSceneAsync(1);
yield return operation;
}
// Update is called once per frame
void Update()
{
//输出加载进度
Debug.Log(operation.progress);
}
}
//----鼠标事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows;
public class Test8 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//鼠标的点击
//按下鼠标 0左键 1右键 2滚轮
if (UnityEngine.Input.GetMouseButton(0))
{
Debug.Log("按下了鼠标左键");
}
//持续按下鼠标
if (UnityEngine.Input.GetMouseButton(0))
{
Debug.Log("持续按下鼠标左键");
}
//拾起鼠标
if (UnityEngine.Input.GetMouseButtonUp(0))
{
Debug.Log("抬起了鼠标左键");
}
//按下键盘按键
if (UnityEngine.Input.GetKeyDown(KeyCode.A))
{
Debug.Log("按下了A");
}
//持续按下按键
if (UnityEngine.Input.GetKey(KeyCode.A))
{
Debug.Log("持续按下A");
}
//抬起键盘按键
if (UnityEngine.Input.GetKeyUp("a"))
{
Debug.Log("松开了A");
}
}
}
//----虚拟按键
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test9 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
////获取水平轴
//float horizontal = Input.GetAxis("Horizontal");
//float vertical = Input.GetAxis("Vertical");
//Debug.Log(horizontal + "" + vertical);
//虚拟按键
if (Input.GetButtonDown("Jump")) {
Debug.Log("空格");
}
}
}
//----屏幕触摸没运行起来
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test10 : MonoBehaviour
{
//开启多点触摸
//Input.multiTouchEnabled = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//判断单点触摸
if (Input.touchCount == 1) {
//触摸对象
Touch touch = Input.touches[0];
//触摸位置
Debug.Log(touch.position);
//触摸阶段
switch (touch.phase) {
case TouchPhase.Began:
break;
case TouchPhase.Moved:
break;
case TouchPhase.Stationary:
break;
case TouchPhase.Ended:
break;
case TouchPhase.Canceled:
break;
}
}
//判断多点触摸 - 无用
if (Input.touchCount == 2)
{
//触摸对象
Touch touch = Input.touches[0];
//触摸位置
Debug.Log(touch.position);
//触摸阶段
switch (touch.phase)
{
case TouchPhase.Began:
break;
case TouchPhase.Moved:
break;
case TouchPhase.Stationary:
break;
case TouchPhase.Ended:
break;
case TouchPhase.Canceled:
break;
}
}
}
}
//----声音控制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test11 : MonoBehaviour
{
//Audioclip
public AudioClip music;
public AudioClip se;
//播放器组件
private AudioSource player;
// Start is called before the first frame update
void Start()
{
player = GetComponent<AudioSource>();
//设定播放的音频片段
player.clip = music;
//循环
player.loop = true;
//音量
player.volume = 0.5f;
//播放
player.Play();
}
// Update is called once per frame
void Update()
{
//按空格切换声音的播放和暂停
if (Input.GetKeyDown(KeyCode.Space)) {
//如果当前正在播放声音
if (player.isPlaying)
{
//暂停
player.Pause();
////停止
//player.Stop();
}
else {
//继续
player.UnPause();
////开始播放
//player.Play();
}
}
}
}
//----Character Controller 角色控制器;进行移动物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test12 : MonoBehaviour
{
private CharacterController player;
// Start is called before the first frame update
void Start()
{
player = GetComponent<CharacterController>();//通过组游戏对象添加 Character Controller 角色控制器;进行移动物体,然后在上面添国脚本即可
}
// Update is called once per frame
void Update()
{
//水平轴
float horizontal = Input.GetAxis("Horizontal");
//垂直轴
float vertical = Input.GetAxis("Vertical");
//创建成一个方向向量
Vector3 dir = new Vector3(horizontal, 0, vertical);
//Debug.DrawRay(transform.position, dir, Color.red);
//朝向该方向移动
player.SimpleMove(dir * 2);
}
}
//----物体落地爆炸销毁(第一步)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test13 : MonoBehaviour
{
//创建一个爆炸预设体
public GameObject Prefab; //注意:这个要把“爆炸”预制体拖动到这里才能运行下面的逻辑。整个逻辑就是:火焰上添加 脚本,脚本调用预设体“爆炸对象” 要拖上去
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
//监听发生碰撞
private void OnCollisionEnter(Collision collision) {
//创建一个爆炸物体
Instantiate(Prefab,transform.position,Quaternion.identity);
//销毁自身 - 有个问题,是一直爆炸
Destroy(gameObject);//注意这个销毁的只是火焰效果,没有销毁爆炸效果
//Debug.Log("------------------");
}
}
//----在预设爆炸上加(销毁一直接爆炸效果)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test13333 : MonoBehaviour
{
float timer = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer > 1) {
Destroy(gameObject);
}
}
}
//----动画(控制锚点)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test18 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F)) {
//触发pickup参数
GetComponent<Animator>().SetTrigger("myTrigger");//pickup
}
}
}
//----动画(人物跑步)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test19 : MonoBehaviour
{
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//水平轴
float horizontal = Input.GetAxis("Horizontal");
//垂直轴
float vertical = Input.GetAxis("Vertical");
//向量
Vector3 dir = new Vector3(horizontal, 0, vertical);
//当用户按下了方向键
if (dir != Vector3.zero)
{
//面向向量
transform.rotation = Quaternion.LookRotation(dir);
//播放跑步动画
animator.SetBool("isRun", true);
//朝向前方移动
transform.Translate(Vector3.forward * 2 * Time.deltaTime);
}
else {
//播放站立动画
animator.SetBool("isRun", false);
}
////随时获取Test参数并打印出来
//Debug.Log(animator.GetFloat("my_quxing1"));
}
//需要定义动画事件
//void leftFoot() {
// Debug.Log("左脚");
//}
//void rightFoot() {
// Debug.Log("右脚");
//}
}
//----动画(IK的使用)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test19 : MonoBehaviour
{
//IK 看向的目标
public Transform target;
//人动画
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//水平轴
float horizontal = Input.GetAxis("Horizontal");
//垂直轴
float vertical = Input.GetAxis("Vertical");
//向量
Vector3 dir = new Vector3(horizontal, 0, vertical);
//当用户按下了方向键
if (dir != Vector3.zero)
{
//面向向量
transform.rotation = Quaternion.LookRotation(dir);
//播放跑步动画
animator.SetBool("isRun", true);
//朝向前方移动
transform.Translate(Vector3.forward * 2 * Time.deltaTime);
}
else {
//播放站立动画
animator.SetBool("isRun", false);
}
////随时获取Test参数并打印出来
//Debug.Log(animator.GetFloat("my_quxing1"));
}
//需要定义动画事件
void leftFoot()
{
Debug.Log("左脚");
}
void rightFoot()
{
Debug.Log("右脚");
}
//IK写到这个方法内 OnAnimatorIK
private void OnAnimatorIK(int layerlndex) {
//设置头部IK
animator.SetLookAtWeight(1);
animator.SetLookAtPosition(target.position);
//设置右手I权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//旋转权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//设置右手IK
animator.SetIKPosition(AvatarIKGoal.RightHand, target.position);
animator.SetIKRotation(AvatarIKGoal.RightHand,target.rotation);
}
}
//----动画(鼠标与导航点击和IK的使用)点那里,自己跑到哪里
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Windows;
public class Test19 : MonoBehaviour
{
private NavMeshAgent agent;
//添加动画组件
private Animator animator;
//IK 看向的目标
public Transform target;
// Start is called before the first frame update
void Start()
{
//获取代理组件-导航
agent = GetComponent<NavMeshAgent>();
//获取动画组件
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//键盘控制移动(保留Test19的功能)
float horizontal = UnityEngine.Input.GetAxis("Horizontal");
float vertical = UnityEngine.Input.GetAxis("Vertical");
Vector3 dir = new Vector3(horizontal, 0, vertical);
//当用户按下了方向键
if (dir != Vector3.zero)
{
//停止导航(如果正在导航)
agent.ResetPath();
//面向向量
transform.rotation = Quaternion.LookRotation(dir);
//播放跑步动画
animator.SetBool("isRun", true);
//朝向前方移动
transform.Translate(Vector3.forward * 2 * Time.deltaTime);
}
else
{
//如果没有键盘输入,检查导航状态
if (agent.velocity.magnitude > 0.1f)
{
//代理在移动,播放跑步动画
animator.SetBool("isRun", true);
}
else
{
//代理停止移动,播放站立动画
animator.SetBool("isRun", false);
}
}
//鼠标点击导航(Test20的原有功能)
if (UnityEngine.Input.GetMouseButtonDown(0))
{
//获取点击位置mousePosition
Ray ray = Camera.main.ScreenPointToRay(UnityEngine.Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//点击位置
Vector3 point = hit.point;
//设置该位置为导航目标点
agent.SetDestination(point);
}
}
////随时获取Test参数并打印出来
//Debug.Log(animator.GetFloat("my_quxing1"));
}
//需要定义动画事件
void leftFoot()
{
Debug.Log("左脚");
}
void rightFoot()
{
Debug.Log("右脚");
}
//IK写到这个方法内 OnAnimatorIK
private void OnAnimatorIK(int layerlndex)
{
//设置头部IK
animator.SetLookAtWeight(1);
animator.SetLookAtPosition(target.position);
//设置右手I权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//旋转权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//设置右手IK
animator.SetIKPosition(AvatarIKGoal.RightHand, target.position);
animator.SetIKRotation(AvatarIKGoal.RightHand, target.rotation);
}
}
//----动画(鼠标与导航点击和IK的使用)点那里,自己跑到哪里, 升级版 - 《当鼠标点击时能不能先面向方向再进行移动,要不鼠标点击然移动太假了,像漂移》
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Windows;
public class Test19 : MonoBehaviour
{
private NavMeshAgent agent;
//添加动画组件
private Animator animator;
//IK 看向的目标
public Transform target;
// 添加变量:是否正在转向中
private bool isRotating = false;
// 添加变量:目标转向角度
private Quaternion targetRotation;
// 添加变量:转向速度
public float rotationSpeed = 5f;
// Start is called before the first frame update
void Start()
{
//获取代理组件-导航
agent = GetComponent<NavMeshAgent>();
//获取动画组件
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//键盘控制移动(保留Test19的功能)
float horizontal = UnityEngine.Input.GetAxis("Horizontal");
float vertical = UnityEngine.Input.GetAxis("Vertical");
Vector3 dir = new Vector3(horizontal, 0, vertical);
//当用户按下了方向键
if (dir != Vector3.zero)
{
//停止导航(如果正在导航)
agent.ResetPath();
//重置转向状态
isRotating = false;
//面向向量
transform.rotation = Quaternion.LookRotation(dir);
//播放跑步动画
animator.SetBool("isRun", true);
//朝向前方移动
transform.Translate(Vector3.forward * 2 * Time.deltaTime);
}
else
{
//如果没有键盘输入,检查导航状态
if (agent.velocity.magnitude > 0.1f && !isRotating)
{
//代理在移动,播放跑步动画
animator.SetBool("isRun", true);
}
else
{
//代理停止移动或正在转向,播放站立动画
animator.SetBool("isRun", false);
}
}
//鼠标点击导航(Test20的原有功能)
if (UnityEngine.Input.GetMouseButtonDown(0))
{
//获取点击位置mousePosition
Ray ray = Camera.main.ScreenPointToRay(UnityEngine.Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//点击位置
Vector3 point = hit.point;
// 计算目标方向
Vector3 direction = (point - transform.position).normalized;
direction.y = 0; // 保持水平
// 如果目标方向有效
if (direction != Vector3.zero)
{
// 设置目标旋转
targetRotation = Quaternion.LookRotation(direction);
isRotating = true;
// 先停止导航,等待转向完成
agent.ResetPath();
animator.SetBool("isRun", false);
// 开始转向协程
StartCoroutine(RotateThenMove(point));
}
}
}
// 处理转向中的旋转
if (isRotating)
{
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
////随时获取Test参数并打印出来
//Debug.Log(animator.GetFloat("my_quxing1"));
}
// 协程:先转向,再移动
IEnumerator RotateThenMove(Vector3 targetPoint)
{
// 等待转向完成(角度差小于1度)
while (Quaternion.Angle(transform.rotation, targetRotation) > 1f)
{
yield return null;
}
// 转向完成,开始移动
isRotating = false;
agent.SetDestination(targetPoint);
}
//需要定义动画事件
void leftFoot()
{
Debug.Log("左脚");
}
void rightFoot()
{
Debug.Log("右脚");
}
//IK写到这个方法内 OnAnimatorIK
private void OnAnimatorIK(int layerlndex)
{
//设置头部IK
animator.SetLookAtWeight(1);
animator.SetLookAtPosition(target.position);
//设置右手I权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//旋转权重
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, 1);
//设置右手IK
animator.SetIKPosition(AvatarIKGoal.RightHand, target.position);
animator.SetIKRotation(AvatarIKGoal.RightHand, target.rotation);
}
}
发表评论 取消回复