触发器:
俩个物体上都有碰撞器至少带有一个刚体,并且俩个物体至少有一个物体打开
碰撞器事件:
1.OnTriggerEnter(Collider other)
当碰撞器进入触发器时OnTriggerEnter被调用。
2.OnTriggerExit(Collider other)
当该碰撞器停止接触触发器时,OnTriggerExit被调用。也就是说,当碰撞器离开触发器时,调用OnTriggerExit。
3.OnTriggerStay(Collider other)
每当碰撞器从进入触发器,几乎每帧调用OnTriggerStay。
触发器实例:实现物体从上方掉落,下发一物体移动,当俩个物体碰到就销毁上方物体,并累加分数
实现随机物体的生成
public GameObject _sphere;
float _creatTime = 1;
float _time = 0;
public static int _score = 0;
void Update()
{
_time += Time.deltaTime;
if (_time > _creatTime)
{
_time = 0;
//随机数
float x = Random.Range(-4f, 4f);
Vector3 pox = new Vector3(x, 8, 1);
Instantiate(_sphere, pox, Quaternion.identity);
//GameObject _timepobj = Instantiate(Resources.Load("Box")) as GameObject;
//_timepobj.transform.position = pox;
//_timepobj.transform.rotation = new Quaternion();
}
实现销毁与分数
void Update()
{
//根据Y轴的位置自动销毁
if (transform.position.y < -5)
{
Destroy(gameObject);
}
}
public void OnTriggerEnter(Collider other)
{
//if (other.name=="Box")
//{
// Destroy(gameObject);
//}
if (other.name == "Cube (1)")
{
Greatqiuti._score += 5;
Debug.Log("_score" + Greatqiuti._score);
Destroy(gameObject);
}
控制物体移动脚本
void Update()
{
float hor = Input.GetAxis("Horizontal");
transform.position += new Vector3(hor, 0, 0) * Time.deltaTime * speed;
}
物理材质
射线(Ray)
RaycastHit射线投射碰撞信息
1.RaycastHit.collider 碰撞器
如果射线什么也没有碰到返回null。如果碰到碰撞器,就返回碰撞器。
2.Physics.Raycast
射线投射
当光线投射与任何碰撞器交叉时为真,否则为假。
实例:(1)实现当一个旋转与移动物体z轴对准另一个物体时生成一条红色射线(在场景视图中可见)
(2)实现点击鼠标让物体慢慢移动到鼠标点击的位置
bool isMove=false;
int speed = 3;
int despeed = 20;
Vector3 _v;
public float _speed = 2000;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
transform.Translate ( new Vector3(0, 0, ver) * Time.deltaTime * speed);
transform.Rotate(new Vector3(0, hor, 0) * Time.deltaTime * despeed);
RaycastHit _hit;
if (Physics.Raycast(transform.position,transform.forward,out _hit,10))
{
if (_hit.collider.name=="Cube")
{
Debug.Log("11");
Debug.DrawLine(transform.position, _hit.point, Color.red);
}
}
if (Input.GetMouseButtonDown(0))
{
RaycastHit _rayhit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out _rayhit))
{
if ( _rayhit.collider.name == "Plane")
{
isMove = true;
_v = _rayhit.point;
}
}
}
if (isMove)
{
transform.position = Vector3.Lerp(transform.position,_v,Time.deltaTime);
}
}
}