觸發器:
倆個物體上都有碰撞器至少帶有一個剛體,并且倆個物體至少有一個物體打開
碰撞器事件:
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);
}
}
}