what:在游戏中模拟真实的物理效果
how:刚体、碰撞器、碰撞检测
一、Rigidbody(刚体):
使游戏对象在物体系统的控制下移动,任何游戏对象只有添加了刚体组件才能受重力的影响
Mess: 质量,数值越大物体下落得越快
Drag: 阻力,数值越大物体速度减慢得越快
Anguylar Drag: 角阻力,数值越大旋转的速度减慢得就越快
Use Gravity: 是否受重力
…
二、碰撞检测:
1.碰撞器: 包含了很多种类(Box Collider,Capsule Collide等),碰撞器必须加到GameObject上
注意:
碰撞的必备条件:
1、两个物体要有碰撞器
2、一个物体要有刚体
碰撞器的种类:
1.Box Collider:盒子碰撞器
2.Sphere Collider:球形碰撞器
3.Capsule Collider:胶囊碰撞器
4.Mesh Collider:网格碰撞器
5.Wheel Collider:车轮碰撞器
2.触发器: 需要在检视面板中碰撞器组件中勾选Is Trigger属性选择框,触发器可以穿透,所以要把重力去掉
//碰撞器的三个方法
void OnCollisionEnter(Collision other)//碰撞时
{
if (other.gameObject.name.Equals("Cube"))//与Cube物体发生碰撞
{
print("Enter......");
}
}
void OnCollisionStay(Collision other)//碰撞中
{
if (other.gameObject.name.Equals("Cube"))
{
print("Stay......");
}
}
void OnCollisionExit(Collision other)/碰撞结束
{
if (other.gameObject.name.Equals("Cube"))
{
print("Exit......");
}
}
//触发器的三个方法
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name.Equals("Cube"))
{
print("Enter......");
}
}
void OnTriggerStay(Collider other)
{
if (other.gameObject.name.Equals("Cube"))
{
print("Stay......");
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.name.Equals("Cube"))
{
print("Exit......");
}
}
项目源代码:
using UnityEngine;
using System.Collections;
public class Move1 : MonoBehaviour
{
Rigidbody r;
float speed = 150;
//定义被克隆的物体
public GameObject Cube;
//
public void Clone()
{
Instantiate(Cube);
}
void Start()
{
//开启协程
StartCoroutine(CloneEnemy());
//获取刚体
r = GetComponent<Rigidbody>();
}
//协程
IEnumerator CloneEnemy()
{
int num = 0;
while (num<=5)
{
int ni = Random.Range(-3, 1);
int nu = Random.Range(-4, 3);
int nt = Random.Range(-6, 5);
yield return new WaitForSeconds(3f);
//随机位置.
Instantiate(Cube, new Vector3(ni, 0, ni), transform.rotation = Quaternion.Euler(0, 0, -26));
Instantiate(Cube, new Vector3(nu, 0, nu), transform.rotation = Quaternion.Euler(0, 0, -26));
Instantiate(Cube, new Vector3(nt, 0, nu), transform.rotation = Quaternion.Euler(0, 0, -26));
Instantiate(Cube, new Vector3(nu, 0, nt), transform.rotation = Quaternion.Euler(0, 0, -26));
num++;
}
}
void Update()
{
float h = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
float v = Input.GetAxis("Vertical") * Time.deltaTime * speed;
Vector3 pos = new Vector3(h, 0, v);
//刚体的位置
r.velocity = pos;
}
void OnTriggerEnter(Collider other)
{
if (other.tag=="BU")//BU:自己定义的标签名
{
Destroy(other.gameObject);
}
}
}