Unity- CatEscape 예제, time
2023. 8. 1.

deltaTime을 사용하면 시간기반 이동을 하는데 쓸 수 있다.

화살 떨어지게 하기

화살과 고양이의 충돌

 

 

Find로 catGo에 오브젝트 넣는다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CatController : MonoBehaviour
{
    public float radius = 1;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //키 입력받기
        if(Input.GetKeyDown(KeyCode.LeftArrow))
        {//왼쪽 화살표를 눌렀다면 x축으로 -3유닛만큼이동
            this.transform.Translate(-3, 0, 0);
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {//오른쪽 화살표를 눌렀다면 x축으로 3유닛만큼이동
            this.transform.Translate(3, 0, 0);
        }

    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(this.transform.position, this.radius);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArrowController : MonoBehaviour
{
    [SerializeField]//SerializeField 애트리뷰트- private멤버도 인스펙터에 노출
    private float speed;

    public float radius = 1;

    private GameObject catGo;

    // Start is called before the first frame update
    void Start()
    {
        this.catGo = GameObject.Find("cat");
        Debug.Log(this.catGo);

      
    }

    // Update is called once per frame
    void Update()
    {
       // Debug.Log(Time.deltaTime);

        //프레임기반 이동
      //  this.gameObject.transform.Translate(0, -1, 0);
        //시간기반 이동
        //속도*방향*시간
        //1f*new Vector3(0,-1,-)*Time.deltatime
        this.transform.Translate(this.speed * Vector3.down * Time.deltaTime);
        if(this.transform.position.y <= -3.88f)//땅에떨어지면
        {
            RemoveArrow();//화살 삭제
        }
        if (this.isCollide())
        {
            Debug.Log("충돌");
            RemoveArrow();//충돌하면 화살 삭제
        }
    }

    void RemoveArrow()
    {
        Destroy(this.gameObject);
        Debug.Log("removeArrow");
    }

    //event함수
    private void OnDrawGizmos()
    {   Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(this.transform.position, this.radius);
    }

    private bool isCollide()
    {
        
        //두 원 사이의 거리
        var dis = Vector3.Distance(this.transform.position, this.catGo.transform.position);

        //반지름 합
        CatController catController = this.catGo.GetComponent<CatController>();
        var sumRadius = this.radius + catController.radius;
        Debug.Log(sumRadius);
        //두 원 사이의 거리가 두 원의 반지름 합보다 크면 false (부딪히지 않음)
        return dis<sumRadius;
    }
}

충돌하면 true를 return.

myoskin