본문 바로가기

Unity

[Unity] 3차 Study : 장애물 & 아이템 Script

[ItemData]

전체 코드

public class ItemData : MonoBehaviour
{
    public int value = 0;    //unity editor 안에서 각 오브젝트에 값을 넣기 위해 public 선언

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

[Item에 따른 점수 계산 흐름]
1) ItemData script를 아이템 오브젝트에 추가하고 각 아이템의 value 설정
2) PlayerController script에서 플레이어와 아이템 충돌 시 score에 value 저장
3) GameManager script에서 score를 받아 합계를 계산

 

 


[EnemyController]

변수 선언부

public float speed = 3.0f;    //적의 이동 속도
public string direction = "left";    //이동 방향
public float range = 0.0f;    //움직이는 범위(editor에서 설정)
Vector3 defPos;    //초기 위치

이동 속도, 방향, 범위는 Unity Editor에서 설정 가능

 


Start()

void Start()
{
    if(direction == "right")    //오른쪽 방향으로 설정 되어있으면 좌우반전
    {
        transform.localScale = new Vector2(-1, 1);
    }
    defPos = transform.position;    //초기 위치 받기
}

적의 에셋이 기본적으로 왼쪽을 바라보는 방향이라 처음 방향이 오른쪽이면 좌우반전을 명시해야함

 


Update()

void Update()
{
    if(range > 0.0f)    //이동 거리가 양수면 Update() 실행
    {
        if(transform.position.x < defPos.x - (range / 2))    //왼쪽 끝 점일 때 방향 전환
        {
            direction = "right";
            transform.localScale = new Vector2(-1, 1);
        }
        if(transform.position.x > defPos.x + (range / 2))    //오른쪽 끝 점일 때 방향 전환
        {
            direction = "left";
            transform.localScale = new Vector2(1, 1);
        }
    }
}

MovingBlock과는 다르게 초기 위치가 총 이동할 간격의 가운데 부분임

때문에 range/2를 기준으로 조건 계산!

 


FixedUpdate()

private void FixedUpdate()
{
    Rigidbody2D rbody = GetComponent<Rigidbody2D>();    //물리적 제어는 FixedUpdate()에서 실행
    if(direction == "right")    //오른쪽 방향이면 x값을 양수로 속도 갱신
    {
        rbody.velocity = new Vector2(speed, rbody.velocity.y);
    }
    else    //왼쪽 방향이면 x값을 음수로 속도 갱신
    {
        rbody.velocity = new Vector2(-speed, rbody.velocity.y);
    }
}

 

 


OnTriggerEnter2D(Collider2D collision)

private void OnTriggerEnter2D(Collider2D collision)
{
    if(direction == "right")    //어떤 물체와 충돌하였을 때 방향을 바꿔줌
    {
        direction = "left";
        transform.localScale = new Vector2(1, 1);
    }
    else
    {
        direction = "right";
        transform.localScale = new Vector2(-1, 1);
    }
}

 

 


[CannonController]

변수 선언부

public GameObject objPrefab;    //포탄 Prefab
public float delayTime = 3.0f;    //지연 시간
public float fireSpeedX = -4.0f;   //발사 vector x
public float fireSpeedY = 0.0f;    //발사 vector y
public float length = 8.0f;    //cannon 활성화 거리 기준

GameObject player;
GameObject gateObj;
float passedTimes = 0;

 

 


Start()

void Start()
{
    Transform tr = transform.Find("gate");    //cannon object의 자식 요소인 gate 위치를 찾음
    gateObj = tr.gameObject;    //gate Object
    player = GameObject.FindGameObjectWithTag("Player");    //Player Object
}

 

 


Update()

void Update()
{
    passedTimes += Time.deltaTime;    //프레임 시간을 더해줌

    //CheckLength(Player 위치) : Cannon과 Player의 위치를 계산하여 return T | F
    if(CheckLength(player.transform.position))
    {
        if(passedTimes > delayTime)    //지연시간보다 프레임 시간이 크면
        {
            passedTimes = 0;    //프레임 시간 0
            //발사 위치는 vector(gate.x, gate.y, cannon.z)
            Vector3 pos = new Vector3(gateObj.transform.position.x, gateObj.transform.position.y, transform.position.z);
            //포탄 prefab으로 gameObject 생성
            GameObject obj = Instantiate(objPrefab, pos, Quaternion.identity);
            //rigid 컴포넌트 가져옴
            Rigidbody2D rbody = obj.GetComponent<Rigidbody2D>();
            //addForce(-x, 0) 힘 가해서 포탄 발사
            Vector2 v = new Vector2(fireSpeedX, fireSpeedY);
            rbody.AddForce(v, ForceMode2D.Impulse);
        }
    }
}

 

 


CheckLength(Vector2 targetPos)

bool CheckLength(Vector2 targetPos)    //cannon과 Player 거리 계산 함수
{
    bool ret = false;
    float d = Vector2.Distance(transform.position, targetPos);    //Vector2.Distance()로 거리계산
    if(length >= d)    //설정된 범위에 들어왔으면 return true
    {
        ret = true;
    }
    return ret;
}

 

 


[ShellController]

전체 코드

public class ShellController : MonoBehaviour
{
    public float deleteTime = 3.0f;    //오브젝트 존재 시간

    void Start()    //경우1)
    {
        Destroy(gameObject, deleteTime);    //포탄 생성 시 deleteTime 후 gameObject 제거
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnTriggerEnter2D(Collider2D collision)    //경우2)
    {
        Destroy(gameObject);    //접촉 시 포탄 제거
    }
}

 

 

 

*교재 : 누구나 할 수 있는 유니티 2D 게임 제작