使用u3d实现一个简单的战斗demo,记下学到的知识点,以备后查。
1.判断是否点中指定物体
if (Input.GetMouseButton(0))
{Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);if (Physics.Raycast(ray, out RaycastHit hit)){//坐标转换Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);mousePositionInWorld.y = 0;this.addAgent(camp, mousePositionInWorld);}
}
2.动态创建预制体
GameObject prefab = Resources.Load<GameObject>("prefabs/changeHp");
GameObject obj = Instantiate(prefab, parent);
预制体资源放置要求如下:
3.NavMeshAgent的使用
参考资料:https://docs.unity3d.com/cn/2022.1/Manual/Navigation.html
4.碰撞检测
碰撞检测的两个必备条件:任意一方具备刚体;碰撞双方均有Collider组件
若勾选IsTrigger,碰撞时则通过下面的函数监听碰撞事件:
private void OnTriggerEnter(Collider collider) { }private void OnTriggerStay(Collider other)
{}private void OnTriggerExit(Collider other)
{}
未勾选,碰撞时通过下面的函数监听碰撞事件:
private void OnCollisionEnter(Collision collision)
{}private void OnCollisionStay(Collision collision)
{}private void OnCollisionExit(Collision collision)
{}
使用示例:
private void OnTriggerEnter(Collider collider)
{if (collider.gameObject.tag=="u_human"){Unit unit = collider.gameObject.GetComponent<Unit>();if (unit && unit._campType != this._bulletCamp){int vv = -Random.Range(50, 120);unit.changeHpValue(vv);this.destorySelf();}}
}private void destorySelf() {Destroy(this.gameObject);
}
实现的效果如下图:
Demo地址:https://github.com/jjinglover/Unity3dDemos