티스토리 뷰

오늘 구현할 것은

  • 플레이어가 어떤 오브젝트에 닿으면 (Trigger 이벤트)
  • 그 오브젝트를 플레이어 뒤쪽에 생성
  • 플레이어의 이동방향데로 따라 붙은 오브젝트도 따라옴

이런 게임을 구현할 수 있음!!!

 

 

Scene안에서의 Player 오브젝트 구조와 Components 설정 

 

Player 스크립트

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

public class Player : MonoBehaviour
{   
    public Transform followerTf;
    public float diameter;

    private List<Transform> followers = new List<Transform>();
    private List<Vector2> followerPos = new List<Vector2>();
    float h;
    float v;
    public float speed = 2f;

    void Start(){
        followerPos.Add(followerTf.position);
    }
    void Update()
    {
       v = Input.GetAxisRaw("Vertical"); // 위아래에 해당하는 키보드가 눌릴때 숫자(-1,0,1) 반환
       h = Input.GetAxisRaw("Horizontal"); // 왼쪽오른쪽에 해당하는 키보드가 눌릴때 숫자(-1,0,1) 반환
       
       //object의 위치를 눌린 입력받은 값에 따라 이동
       transform.position += new Vector3(h, v, 0) * speed * Time.deltaTime;
    }
    
    void LastUpdate(){
        MakeCivilianFollow();
    }

    void MakeCivilianFollow(){
        float distance = ((Vector2)followerTf.position - followerPos[0]).magnitude; //이전 위치와 현재위치사이의 거리 
        
        if (distance > diameter) { 만약 이전 위치와 현재위치 사이의 거리가 , 반지름 보다 커졌을 경우
            Vector2 direction = ((Vector2)followerTf.position - followerPos[0]).normalized; // 방향정보
            
            followerPos.Insert(0, followerPos[0] + direction*diameter); //반지름 길이만큼 다음 위치 재조정
            followerPos.RemoveAt(followerPos.Count - 1); // 마지막 위치정보 없애기 (뒤쳐짐 방지)
            
            distance -= diameter; // 거리 초기화
        }
        
        //follower의 숫자만큼
        for (int i=0; i<followers.Count; i++){
            // 각각의 follower들이 앞선 위치로 이동 follower[i]의 현재 위치는 followerPos[i+1]임 
            // 왜냐면 애초에 follower가 한명도 없을 때도 시작 정도를 가지고 있어야 하기 때문
            followers[i].position = Vector2.Lerp(followerPos[i+1], followerPos[i], distance/diameter);
        }    
    }

    public void AddFollower(){
        //맨 마지막 위치에 새로운 follower생성
        Transform follower = Instantiate(followerTf, followerPos[followerPos.Count-1], Quaternion.identity, transform);
        followers.Add(follower); // follower 추가
        followerPos.Add(follower.position); // follower 위치 추가 (맨 마지막 위치)
    }
}

 

 

Civilain 오브젝트의 Components

Civilian (충돌 당하는 대상) 스크립트

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

public class Civilian : MonoBehaviour
{
    public Player player;

    void OnTriggerEnter2D(Collider2D col){
        if(col.gameObject.tag == "Player"){
            player.AddFollower();
            Destroy(gameObject, 0.02f);
        }
    }
}

 

잘 따라다닌다!

끝.

 


참고사항

(Unity) 물체 생성 : Object.Instantiate (복사할 대상, 위치, 각도, 부모)

 

(C#) 리스트의 method

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0 

 

List<T> Class (System.Collections.Generic)

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

docs.microsoft.com

Add(T) Adds an object to the end of the List<T>. 리스트 맨뒤에 오브젝트 추가 
Clear() Removes all elements from the List<T>. 리스트에 있는 모든 오브젝트 제거
Insert(Index, T) Inserts an element into the List<T> at the specified index. 특정 인덱스의 위치로 오브젝트 추가
Remove(T) Removes the first occurrence of a specific object from the List<T>. 가장 처음 나타나는 type 오브젝트제거
RemoveAll(T) Removes all the elements that match the conditions defined by the specified predicate. 모든 일치하는 type 오브젝트 제거
RemoveAt(Index) Removes the element at the specified index of the List<T>. 특정 인덱스에 있는 오브젝트제거

 

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함