'잡다한것들전부'에 해당되는 글 207건

  1. 2014.02.25 killTrigger -> 모든 적과 주인공 충돌(강) - Removver 스크립트
  2. 2014.02.25 플레이어의 체력 - PlayerHealth
  3. 2014.02.25 플레이어 무기 발사 - gun 스크립트
  4. 2014.02.25 주인공을 따라다니는 카메라
  5. 2014.02.25 플레이어 컨트롤 스크립트
  6. 2014.02.25 배경 시차 스크롤 카메라의 움직임에따라
  7. 2014.02.10 버튼 다운로드 사이트
  8. 2014.02.04 유니티 공식 사용자 매뉴얼
  9. 2014.02.04 유니티 참고 인디 게임 링크
  10. 2014.02.04 게임 매니악스 책 총 3권

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

주인공을 따라다니는 카메라

|


슈퍼마리오의 카메라 처럼 일정 거리에서는 카메라가 움직이지 않고 일정거리를 넘어갔을때만 카메라가 이동함.


// If the player has moved beyond the x margin...

if(CheckXMargin())

// ... the target x coordinate should be a Lerp between the camera's current x position and the player's current x position.

targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime);


// If the player has moved beyond the y margin...

if(CheckYMargin())

// ... the target y coordinate should be a Lerp between the camera's current y position and the player's current y position.

targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.deltaTime);


-> 마진 체크 후 카메라 이동


->Lerp 가 결국에는 targetY에 대입이 되며 targetY값은 계속 증가 결국 플레이어의 위치값과 똑같아짐









// The target x and y coordinates should not be larger than the maximum or smaller than the minimum.

targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);

targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);


// Set the camera's position to the target position with the same z component.

transform.position = new Vector3(targetX, targetY, transform.position.z);


-> 카메라 최대 거리 제한






결국엔 히어로의 값이랑 메인카메라랑 값이 똑같아 져야 되지만 카메라의 위치를 제한을 둬서 일정거리까지는 이동을 하지 못함








Trackback 0 And Comment 0

플레이어 컨트롤 스크립트

|


Taunt -> 점수 획득시 호출 -> 플레이어 웃음 소리 랜덤으로 발생 -> 같은 웃음소리면 다시 호출해서 다른 웃음소리가 나올때까지 호출함(재귀호출)


Linecast-> 라인 캐스트를 사용해서 플레이어의 밑이 Ground인지 파악한다. -> 오브젝트의 레이어 이름이 Ground여야 됨..


groundCheck -> 빈 게임 오브젝트를 캐릭터 밑에 위치 시킴. 인스펙터창에서 모양을 지정해줄수있어서 어디 위치했는지 쉽게 알수 있음.


if(h * rigidbody2D.velocity.x < maxSpeed)

rigidbody2D.AddForce(Vector2.right * h * moveForce);

if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)

rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);


플레이어의 속도가 최대속도보다 아래면 힘을주고 아니면 속도를 최대속도로 제한해준다.


if(h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if(h < 0 && facingRight)
// ... flip the player.
Flip();

플레이어의 모양을 보고 왼쪽이면 왼쪽을 바라보게 오른쪽이면 오른쪽으로 바라보게 한다.


if(jump)
{
// Set the Jump animator trigger parameter.
anim.SetTrigger("Jump");

// Play a random jump audio clip.
int i = Random.Range(0, jumpClips.Length);
AudioSource.PlayClipAtPoint(jumpClips[i], transform.position);

// Add a vertical force to the player.
rigidbody2D.AddForce(new Vector2(0f, jumpForce));

// Make sure the player can't jump again until the jump conditions from Update are satisfied.
jump = false;
}

점프 중이면. 랜덤으로 점프 사운드를 재생하고 위쪽으로 힘을 가한다(AddForce)


-> 모든 물리관련 동작은 FixedUpdate()에서 실행한다.


솔직히 아직도 재귀함수에 대한 이해가 부족한거 같음
된다는건 알고있지만 뭔가 이상하다..





Trackback 0 And Comment 0

배경 시차 스크롤 카메라의 움직임에따라

|


배경 시차 스크롤 카메라의 움직임에 따라서 배경의 움직임이  달라짐.

Background 빈 오브젝트에 각각의 값들을 집어넣으면 그 값들은 각각의 속도가 다름..

뭔가 파악하기 어려운 소스지만.. 일단 대강은 이해가 감.




parallax.unitypackage


카메라를 이동가능하게 만듬..



parallaxScale -> 시차 스크롤링 속도 (카메라의 움직임에 따라 값이 클수록 더 빨리 배경이 움직임)


parallaxReductionFactor -> 각 레이어 별 시차 스크롤 속도 차이 값이 클수록 각 레이어별로 속도 차이가 크다.


smothing -> Lerp 함수에 입력된 값


Trackback 0 And Comment 0

버튼 다운로드 사이트

|

http://www.button-download.com/

Trackback 0 And Comment 0

유니티 공식 사용자 매뉴얼

|

http://unitykoreawiki.com/index.php?n=KrMain.TableOfContents

Trackback 0 And Comment 0

유니티 참고 인디 게임 링크

|

http://blue-brick.com/SUPERHOT/

Trackback 0 And Comment 0

게임 매니악스 책 총 3권

|

게임 알고리즘 관련 책들 좋은 책들이 많이 나오네요.



게임 매니악스 탄막 게임 알고리즘

저자
마츠우라 켄이치로, 츠카사 유키 지음
출판사
한빛미디어 | 2014-02-01 출간
카테고리
컴퓨터/IT
책소개
이 책은 C++ 기반으로 37가지 탄막을 만드는 방법을 알려줍니...
가격비교





게임 매니악스 슈팅 게임 알고리즘

저자
마츠우라 켄이치로, 츠카사 유키 지음
출판사
한빛미디어(주) | 2013-10-21 출간
카테고리
컴퓨터/IT
책소개
갤러그의 편대 비행, 제비우스의 종스크롤, 메탈 슬러그의 횡스크...
가격비교





게임 매니악스 퍼즐 게임 알고리즘

저자
마츠우라 켄이치로, 츠카사 유키 지음
출판사
한빛미디어 | 2013-12-23 출간
카테고리
컴퓨터/IT
책소개
이 책이 제시하는 핵심 내용 퍼즐 게임을 구성 요소별로 다루는 ...
가격비교



Trackback 0 And Comment 0
prev | 1 | 2 | 3 | 4 | 5 | 6 | ··· | 21 | next