응용프로그램/유니티(Unity)

Unity - 충돌감지관련

zelkova 2016. 11. 14. 13:53

<목차로 돌아가기>


  충돌감지관련


출처 : Sebastian Lague의 동영상 강의


  1. using UnityEngine; 
  2. using System.Collections;

  3.  public class Projectile : MonoBehaviour {

  4.     public LayerMask collisionMask;
  5.     float speed = 10;

  6.     public void SetSpeed(float newSpeed)
  7.     {
  8.        speed = newSpeed;
  9.     }

  10.     void Update () {
  11.         float moveDistance = speed * Time.deltaTime;
  12.         CheckCollisioins(moveDistance);
  13.         transform.Translate(Vector3.forward * Time.deltaTime * speed);
  14.     
  15. }

  16.     void CheckCollisioins(float moveDistance)
  17.     {
  18.         Ray ray = new Ray(transform.position, transform.forward);
  19.         RaycastHit hit;

  20.     if(Physics.Raycast(ray, out hit, moveDistance, collisionMask, 
  21.         QueryTriggerInteraction.Collide))
  22.     {
  23.         OnHitObject(hit);
  24.     }

  25.     }
  26.     void OnHitObject(RaycastHit Hit)
  27.     {
  28.         print(Hit.collider.gameObject.name);
  29.         GameObject.Destroy(gameObject);
  30.     }
  31. }


반응형