创作人 Leo
编辑时间 Mon Aug 15,2022 at 15:47
Rigid body 刚体
可以为游戏对象赋予物理属性,使游戏对象在物理系统的控制下接受推力与扭力,从而实现现实世界中的运动效果。
在游戏制作过程中,只有为游戏对象添加了刚体组件,才能使其受到重力影响。
刚体是物理引擎中最基本的组件。在物理学中,刚体是一个理想模型。
通常把在外力作用下,物体的形状和大小(尺寸)保持不变,而且内部各部分相对位置保持恒定(没有形变)的理想物理模型称为刚体。
在一个物理引擎中,刚体是非常重要的组件,通过刚体组件可以给物体添加一些常见的物理属性,如质量、摩擦力、碰撞参数等。
通过这些属性可以模拟该物体在 3D 世界内的一切虚拟行为,当物体添加了刚体组件后,它将感应物理引擎中的一切物理效果。
Unity 3D 提供了多个实现接口,开发者可以通过更改这些参数来控制物体的各种物理状态。
刚体在各种物理状态影响下运动,刚体的属性包含 Mass(质量)、Drag(阻力)、Angular Drag(角阻力)、Use Gravity(是否使用重力)、Is Kinematic(是否受物理影响)、Collision Detection(碰撞检测)等。
collider
碰撞体,在 Unity 3D 的物理组件使用过程中,碰撞体需要与刚体一起添加到游戏对象上才能触发碰撞。
值得注意的是,刚体一定要绑定在被碰撞的对象上才能产生碰撞效果,而碰撞体则不一定要绑定刚体。
GameObject
Unity 场景中所有实体的基类
常用操作:
Transform
Transform 类提供多种方式来通过脚本处理游戏对象的位置、旋转和缩放,以及与父和子游戏对象的层级关系
MonoBehaviour
MonoBehaviour 是Unity 脚本的基类,提供了访问绑定的游戏对象以及组件的功能,和处理事件消息功能,允许用户管理和使用协程;
MonoBehaviour 事件处理:
public class TestRangeMapScript : MonoBehaviour
{
void OnGUI()
{
// 程序运行时绘制 GUI
}
void Awake()
{
// Start and Awake work in similar ways except that Awake is called first and, unlike Start, will be called even if the script component is disabled.
// https://gamedevbeginner.com/start-vs-awake-in-unity/
}
void Start()
{
// 程序开始运行执行的函数
}
void Update()
{
// 组件的帧函数
}
}
获取绑定的对象或组件
public class TestRangeMapScript : MonoBehaviour
{
public void test()
{
Debug.Log("hello test");
}
// Start is called before the first frame update
void Start()
{
// transform 获取当前绑定到的 GameObject 的 transform 组件
var position = transform.position;
Debug.Log(string.Format("position {0}", position));
// gameObject 获取当前绑定到的 GameObject 实例,并从中获取组件
gameObject.GetComponent<TestRangeMapScript>().test();
}
}
参考:
void removeAllCube()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("RangeMapBlock");
if (objs.Length > 0)
{
foreach (GameObject obj in objs)
{
DestroyImmediate(obj);
}
}
objs = GameObject.FindGameObjectsWithTag("RangeMapRoad");
if (objs.Length > 0)
{
foreach (GameObject obj in objs)
{
DestroyImmediate(obj);
}
}
}
// 通过 GameObject 获取
GameObject background = GameObject.Find("RangeMapBackground");
if (background != null)
{
// Close background
background.SetActive(false);
}
// 通过 transform 获取
// The way only find children node.
Transform backgroundTF = transform.Find("RangeMapBackground");
if (backgroundTF != null)
{
//Debug.Log("background exists");
// Open background
backgroundTF.gameObject.SetActive(true);
}
参考
Unity3D-场景中3D物体添加点击事件
Unity UGUI —— 鼠标穿透UI问题(Unity官方的解决方法)
Unity - GraphicRaycaster