'잡다한것들전부/공식예제'에 해당되는 글 13건

  1. 2015.02.22 MovingObject, player, enemy
  2. 2015.02.22 맵 생성 스크립트 - BoardManager
  3. 2014.02.25 배경 생성 관련 스크립트 - BackgroundPropSpawner
  4. 2014.02.25 몬스터 관련 함수 - Enemy 스크립트
  5. 2014.02.25 점수 표현 - Score
  6. 2014.02.25 폭탄과 구급 상자 - Bomb Pickup, Bomb
  7. 2014.02.25 물체 파괴 함수 -> Destroyer 스크립트
  8. 2014.02.25 killTrigger -> 모든 적과 주인공 충돌(강) - Removver 스크립트
  9. 2014.02.25 플레이어의 체력 - PlayerHealth
  10. 2014.02.25 플레이어 무기 발사 - gun 스크립트

MovingObject, player, enemy

|
Trackback 0 And Comment 0

맵 생성 스크립트 - BoardManager

|






Loader 에서 GameManager 프리팹 생성. GameManger 프리팹에 BoardManager 존재.
BoardManager에는 해당되는 프리팹들 모두 연결됨.
- Floor
- Food
- Enemy
- OuterWall
여기 있는 프리팹 배열 중에 랜덤으로 뿌려줌.


gridPositions List 에  x = 1~columns-1

 y = 1 ~ rows-1

까지의 위치값들을 전부 저장하고. 랜덤으로 위치값을 지정해줄때. 리스트에 있는 값들을 하나하나 뽑아서 사용함.

RemoveAt을 사용해서 뽑았던 값들은 다시 나오지 않도록 제거함.

Enemy 의 수는 Mathf.Log 함수를 사용해서 레벨이 올라가면 적의 숫자를 올라가도록 설정했음..




Trackback 0 And Comment 0

배경 생성 관련 스크립트 - BackgroundPropSpawner

|


backgroundProp -> 이 변수에 각각 버스, 백조, 택시등을 넣어줄수있음


코루틴으로 Spawn() 함수를 계속 호출함


waitTime -> 다음 프리팹이 생성될 시간 랜덤값(최소시간 ~ 최대시간)

facingLeft->오른쪽에서 나올지 왼쪽에서 나올지



와; 코루틴을 사용해서 while문 돌려주고 그 안에서 propInstance 의 값을 체크해서 범위를 넘으면 삭제..

대박;


결국엔 Destroy 하면 해당 while문은 null이 되고 코루틴을 빠져나옴.




Trackback 0 And Comment 0

몬스터 관련 함수 - Enemy 스크립트

|
벌레와 우주선이 있는데요

벌레는 꼬리부분을 개별적으로 짤라주고 축을 오른족으로 두어서 꼬리의 크기를 늘렸다 줄였다하면서 애니메이션을 줄수있습니다.


둘다 Enemy 스크립트를 가지고 있지만 익스펙터에서 값을 조정해서 사용한다.











deadEnemy = 죽는 모습 스프라이트

damagedEnemy = 몬스터 공격 당할시 스프라이트

deathClips = 사운드

hundredPointsUI -> 적을 죽이면 100 생성

deathSpinMin -> 죽을때 떨어지는 각도


ren - > 몸통 렌더러

frontCheck -> 바로 앞에 있는 값 체크




Collider2D[] frontHits = Physics2D.OverlapPointAll(frontCheck.position, 1); -> 바로 앞에 있는 모든 값 체크

레이어 마스크 값이 1이면 모든 값;

그중에 Obstacle 값이면 Flip 함수실행 -> 좌우 반전

움직임 조절 rigidbody2D.velocity = new Vector2(transform.localScale.x * moveSpeed, rigidbody2D.velocity.y);


죽으면 죽는 함수 실행

if(HP <= 0 && !dead)

// ... call the death function.

Death ();




void Death() 함수


모든 스프라이트 렌더러를 불러와서 다 안보이게 한다.

그리고 바디 렌더러(ren)는 보이게 하고

그 렌더러의 스프라이트를 죽는 모습으로 변경하고

스코어를 100점 올려주고 dead 를 true 로 변경


리지드바디의 앵글을 고정시켜버린다.(떨어질때 변경되지 않도록)

AddTorque -> 함수를 사용하여 축을 중심으로 회전되게한다.


그리고 주인공 스크립트에서 했던것과 마찬가지로 모든 콜라이더를 isTrigger 처리 해줘서 적이 떨어지도록 한다

스코어는 적의 위치 바로 위에 생성되게 한다.







Trackback 0 And Comment 0

점수 표현 - Score

|

UI 의 스코어에 붙어있는 스크립트


화면 위에 있는 점수





guiText 값 변경 해주고

점수를 얻으면 Taunt 함수를호출




Trackback 0 And Comment 0

폭탄과 구급 상자 - Bomb Pickup, Bomb

|

bombCrate -> crate, parachute

FloatDown 애니(떨어질때 흔들흔들하는모션) 와 BombLanding(떨어지고 나서 낙하산이 없어지는모션) 애니로 구성되있음






landed -> 현재 땅인지 체크

폭탄은 서클 콜라이더와 박스 콜라이더로 구성되있고 서클콜라이더는 is Trigger 체크 되있음

그래서 OnTriggerEnter 함수를 호출할수잇음. 박스콜라이더는 땅과 부딪히게 할려고 부착한 상태인듯. isTrigger 시 충돌 무시해버리고 통과되기때문.


Player 와 부딪힐 경우에는 플레이어의 폭탄 개수를 늘려주고 삭제해버림.


그리고 땅과 부딪힐경우에는 else if(other.tag == "ground" && !landed)


Ladn 애니메이션을 실행시키고

Create 폭탄의 부모 오브젝트를 null값으로 만들어준다.

그리고 리지드바디를 추가시킴(추가가 안될시 플레이어와 물리효과를 집어널수없기때문,.)





explosionParticle -> 은 히어라이키에 한개만 존재함 이함수를 재활요해서 계속 사용함





폭탄관련함수

if(transform.root == transform)

StartCoroutine(BombDetonation());

플레이어가 알트 버튼을 눌러서 폭파 시킬때 실행됨 최상위 오브젝트가 없을때(Create일때) -> LayBombs 스크립트에서 실행






Explode() -> 외부에서 실행됨 폭탄이 내려오는데 플레이어가 총으로 맞춘다던가

bombLaid 를 false로 만들어줌.

pickupSpawner -> 픽업매니저 스크립트 -> PickupSpawner 구급상자와 폭탄 생성



pickupSpawner.StartCoroutine(pickupSpawner.DeliverPickup()); -> 아이템 재생성


Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position, bombRadius, 1 << LayerMask.NameToLayer("Enemies"));

반경 원안에 있는 적들 배열에 집어넣기
foreach(Collider2D en in enemies)
{
// Check if it has a rigidbody (since there is only one per enemy, on the parent).
Rigidbody2D rb = en.rigidbody2D;
if(rb != null && rb.tag == "Enemy")
{
// Find the Enemy script and set the enemy's health to zero.
rb.gameObject.GetComponent<Enemy>().HP = 0;

// Find a vector from the bomb to the enemy.
Vector3 deltaPos = rb.transform.position - transform.position;

// Apply a force in this direction with a magnitude of bombForce.
Vector3 force = deltaPos.normalized * bombForce;
rb.AddForce(force);
}
}



적들의 체력을 0으로 만들고 적들을 튕겨내버림



explosionFX.transform.position = transform.position;

explosionFX.Play();


이펙트 위치 설정 및 실행











플레이어에 붙어있는 스크립트


bombLaid -> 폭탄 발사여부 - > Explode 함수가 실행되야 false로 변함 

bombCount -> 폭탄 개수

알트 버튼 누르면 발사






Trackback 0 And Comment 0

물체 파괴 함수 -> Destroyer 스크립트

|
Splash -> 강물빠지는거

explosionCircle -> 폭탄 사용시 잠시 원처럼 뜨는것.

ui_100points -> 적 죽이면 점수 화면에 뿌려줄때







Splash 와 Score 는 에니메이션으로 구성되있고 에니메이션 이벤트의 마지막에 -> DestroyGameObject를 실행시킨다.

explosionCircle 은 발생과 동시에 0.1초만에 오브젝트를 삭제시킨다.







destroyOnAwake -> 시작과 동시에 삭제시킬지 여부

findChild -> 자기의 자식을 삭제시킬지 여부

namedChild - > 자식을 삭제시킬때 삭제시킬 자식 이름


DestroyChildGameObject -> 자식 삭제

DisableChildGameObject -> 자식을 비활성화로

DestroyGameObject -> 자기 자신 삭제




Trackback 0 And Comment 0

killTrigger -> 모든 적과 주인공 충돌(강) - Removver 스크립트

|


강물 위치에 배치되있음.

Remover 스크립트가 할당되있고, 몬스터가 강물에 빠지면 해당 오브젝트를 제거하고 플레이어가 빠지면 특정 작업을 한후 재시작함.




// If the player hits the trigger...

if(col.gameObject.tag == "Player")

{

// .. stop the camera tracking the player

GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraFollow>().enabled = false;


// .. stop the Health Bar following the player

if(GameObject.FindGameObjectWithTag("HealthBar").activeSelf)

{

GameObject.FindGameObjectWithTag("HealthBar").SetActive(false);

}


// ... instantiate the splash where the player falls in.

Instantiate(splash, col.transform.position, transform.rotation);

// ... destroy the player.

Destroy (col.gameObject);

// ... reload the level.

StartCoroutine("ReloadGame");

}

else

{

// ... instantiate the splash where the enemy falls in.

Instantiate(splash, col.transform.position, transform.rotation);


// Destroy the enemy.

}


메인카메라의 CameraFollow 스크립트 기능 끄기

HealthBar 활성화 상태이면 안보이게 하기 (activeSelf -> 오브젝트 활성화 여부 체크)

Splash 프리팹 생성 -> 강물 빠지는 모양 -> 프리팹에는 Destroyer 스크립트 연결되있음(애니메이션 마지막 부부분에서 자기자신을 삭제해줌)

플레이어 제거

ReloadGame 코루틴 실행





IEnumerator ReloadGame()

{

// ... pause briefly

yield return new WaitForSeconds(2);

// ... and then reload the level.

Application.LoadLevel(Application.loadedLevel);

}


2초후 게임 다시 실행




Trackback 0 And Comment 0

플레이어의 체력 - PlayerHealth

|






Health - > 체력

repeatDamagePeriod -> 데미지를 받고나서 다시한번 받을때 까지 간격

ouch clips -> 아픈 사운드 종류별로;

Hurt Force -> 플레이어와 적 충돌시 발생되는 힘

Damage Amount -> 깍이는 체력양








healthBar -> 체력 바는 피봇 위치를 왼쪽으로 해준다.

healthScale -> 이값을 이용하여 체력 게이지의 크기를 줄여줌



OnCollisionEnter2D -> 캐릭터와 충돌 발생시


if(col.gameObject.tag == "Enemy")  

{

// ... and if the time exceeds the time of the last hit plus the time between hits...

if (Time.time > lastHitTime + repeatDamagePeriod) 

{

// ... and if the player still has health...

if(health > 0f)

{

// ... take damage and reset the lastHitTime.

TakeDamage(col.transform); 

lastHitTime = Time.time; 

}

}

}


Enemy 태그와 충돌시

그리고 repeatDamagePeriod 간격이 지날때만 실행 -> 인스펙터 창에서 조절 가능

체력이 0보다 클때는 TakeDamage 함수 실행



// If the player doesn't have health, do some stuff, let him fall into the river to reload the level.

else

{

// Find all of the colliders on the gameobject and set them all to be triggers.

Collider2D[] cols = GetComponents<Collider2D>();

foreach(Collider2D c in cols)

{

c.isTrigger = true;

}


// Move all sprite parts of the player to the front

SpriteRenderer[] spr = GetComponentsInChildren<SpriteRenderer>();

foreach(SpriteRenderer s in spr)

{

s.sortingLayerName = "UI";

}


// ... disable user Player Control script

GetComponent<PlayerControl>().enabled = false;


// ... disable the Gun script to stop a dead guy shooting a nonexistant bazooka

GetComponentInChildren<Gun>().enabled = false;


// ... Trigger the 'Die' animation state

anim.SetTrigger("Die");

}


체력이 0보다 작을때는(죽을때) 모든 물체의 충돌을 무시하기 위해서 모든 충돌체를 isTrigger 해주고

모든 스프라이트 렌더러의 레이어 값을 UI 로 설정해줌->최상위 오브젝트로(맨위에 보이게)

그리고 PlayerControl 스크립트를 꺼주어 캐릭터가 못움직이게 한다

Gun 스크립트를 꺼주어서 총을 발사를 못하게 한다.

마지막으로 죽는 애니메이션을 실행시킨다.





플레이어가 충돌시 실행되는 함수


void TakeDamage (Transform enemy)

{

// Make sure the player can't jump.

playerControl.jump = false;


// Create a vector that's from the enemy to the player with an upwards boost.

Vector3 hurtVector = transform.position - enemy.position + Vector3.up * 5f;


// Add a force to the player in the direction of the vector and multiply by the hurtForce.

rigidbody2D.AddForce(hurtVector * hurtForce);


// Reduce the player's health by 10.

health -= damageAmount;


// Update what the health bar looks like.

UpdateHealthBar();


// Play a random clip of the player getting hurt.

int i = Random.Range (0, ouchClips.Length);

AudioSource.PlayClipAtPoint(ouchClips[i], transform.position);

}


충돌발생시 점프를 못하게하고

적과 부딪힌 방향으로 캐릭터를 튕기게 해준다. -> rigidbody2D.AddForce(hurtVector * hurtForce);

그리고 체력을 깍고 UpdateHealthBar함수를 실행시켜 게임내에서 체력바를 적용되게 한다.

마지막으로 오디오 사운드를 실행시킴..



public void UpdateHealthBar ()

{

// Set the health bar's colour to proportion of the way between green and red based on the player's health.

healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);


// Set the scale of the health bar to be proportional to the player's health.

healthBar.transform.localScale = new Vector3(healthScale.x * health * 0.01f, 1, 1);

}


체력이 깍일수록 점점 빨간색으로 변함.

health 값으로 체력바의 길이 조절










체력바 에 붙는 스크립트

주인공위에 항상 따라다님.

ui_healthDisplay




Trackback 0 And Comment 0

플레이어 무기 발사 - gun 스크립트

|



프리팹을 생성해줄때 Rigidbody2D 로 생성해줄수도 있음.. 생성해주고 나서 리지드바디의 velocity 값을 수정해서 로켓이 발사되는 위치를 지정해줌.

transform.root -> 등을 사용하여 최상위 오브젝트에 접근한다.


Trackback 0 And Comment 0
prev | 1 | 2 | next