2013年12月1日 星期日

Unity-連接Arduino+碰撞事件




  • 先在Arduino端設置四顆按鈕,並在按下後傳送1、2、3、4,分別控制物體的上下左右
  1. Serial.write(3);
  2. Serial.flush();
  3. delay(20);

  • Unity接收Arduino傳來的數值

  1. file->Build and Setting->Player Setting->API Compatibility Level->.NET 2.0
  2. Assets->create->c#
  3. using System.IO.Ports
  4. SerialPort sp = new SerialPort("COM7",9600);
  5. 在Start function 中 開啟sp->sp.Open()、sp.ReadTimeout = 1
  6. 在updata function 中 先確認sp是否正確->sp.IsOpen(true/false)-->try and catch
  7. 改變object的位置->transform.Translate(Vector3.left*speed,Space.World)
  8. 利用Vector3的left、reght、forward、back、up、down來改變三軸在空間中的位置

  • Unity碰撞事件

  1. 在想撞人的物體上加上剛體:component->Physics->Rigidbody
  2. 撞人和被撞至少有一個開啟Is Trigger才撞得進去:Sphere Collider->Is Trigger
  3. 當撞到且撞得進去時呼叫:void OnTriggerEnter(Collider other)  (有勾Is Trigger)
  4. 當撞到但撞不進去時呼叫:void OnCollisionEnter(Collision collisionInfo) (都沒勾Is Trigger)