충돌 감지후 스파크

 

void OnCollisionEnter(Collision col)   {
  if(col.gameObject.tag == "Bullet")
  
  {
         hit++;
         audio.PlayOneShot(firstSound,1.0f);      

GameObject newSpark1 =

          (GameObject)Instantiate(prefab1,col.transform.position,Quaternion.identity);   
   
          Destroy (col.gameObject);      

          Destroy (newSpark1,0.5f);     
  }
  
  if(hit == 3)
  {
          GetComponent<CapsuleCollider>().enabled = false;   

          Explosion();
  }
 } 

 

 

AddComponent, AddForce

 void Explosion()
 {
  audio.PlayOneShot(secondSound,1.0f);
          //<rigidbody> is used to make phishical effect!!
  GameObject newSpark2 = Instantiate(prefab2,transform.position,Quaternion.identity)as GameObject;
  
  
  gameObject.AddComponent<Rigidbody>();
  GetComponent<Rigidbody>().AddForce(Vector3.up*1000.0f);
  
  Destroy(newSpark2,2.0f);
  Destroy(gameObject,2.5f);
  
 }

 

 

rigidbody.AddForce(Vector3.forward * Speed);

 

 

Gizmo

 public class MyGizmo : MonoBehaviour {

 public Color _color = Color.yellow;
 public float _radius = 0.2f;
 
 void OnDrawGizmos()
 {
        Gizmos.color = _color;
        Gizmos.DrawSphere(transform.position,_radius);
 }
}

 

 

멀티쓰레드, 총알발사

 if(Input.GetButtonUp("Fire1"))
  {
            StartCoroutine("Fire");
  }

 

 

IEnumerator Fire()
 {                  // sound, where? , how big?
      AudioSource.PlayClipAtPoint(BulletSound,firepos.position,1.0f);    

      GameObject newBullet = (GameObject)  

                      Instantiate(BulletPrefab,firepos.position,Quaternion.identity);
       Destroy(newBullet, 3.0f);
       yield return null;     // Do next Frame~!!
 }

 

 

foreach , SendMessage

 foreach(GameObject MonsterMecanim in GameObject.FindGameObjectsWithTag("Monster")) 

  {
             MonsterMecanim.SendMessage("YouWin");   //cal method
  }
  

 

Rotate

 gameObject.transform.Rotate(Vector3.up * Speed * Time.deltaTime);

 

OnTriggerEnter, OnTiriggerExit

 public Light streetLight;
 public AudioClip LightSound;
 
 
 void OnTriggerEnter(Collider hit)  //catch conflict without phishical effet!
 {
  if(hit.gameObject.tag == "Player")
  {
        audio.PlayOneShot(LightSound,1.0f);
        streetLight.light.enabled = true;
  }
 }
 
 void OnTriggerExit(Collider hit)  //catch conflict without phishical effet!
 {
  if(hit.gameObject.tag == "Player")
  {
        audio.PlayOneShot(LightSound,1.0f);
        streetLight.light.enabled = false;
  }
 }

 

 

몬스터생성 (GetComponentsInChildren,Time.time,오브젝트 개수 파악)

 public GameObject Monster;
 public GameObject Zombie;
 public Transform[] point;      //it makes me use other GameObjects. Declare array...
 public float CreateTime = 2.0f;
 

 void Start () {
  point = GameObject.Find ("SpawnPoint").GetComponentsInChildren<Transform>();     //access SpawnPoint and its childrens
 }
 
  void Update () {
  
  if(Time.time > CreateTime)
  {
   if(GameObject.FindGameObjectsWithTag("Monster").Length +      

                             GameObject.FindGameObjectsWithTag("Zombie").Length <=5)
   {
               CreateMonster();
               CreateTime = Time.time + 2.0f;
   }
  }
 
 }// end of Update().
 
 
 void CreateMonster()
 {
            int idx = Random.Range(1,point.Length);
            Instantiate(Monster,point[idx].position,Quaternion.identity);
            Instantiate(Zombie,point[idx].position,Quaternion.identity);
 } //end of CreateMonster().

 

 HpBar

 public Texture ForegroundTexture;
 public Texture BackgroundTexture;
 public Texture2D DamageTexture;  //use 2D UI and change color

 
 void OnGUI()  //draw picture method
 {
  Rect rect = new Rect(10,6,Screen.width/2-20,BackgroundTexture.height);  //(x,y,width,height)
  
  GUI.DrawTexture(rect,BackgroundTexture);
  
  float hp = PlayerCtrl.hp;
  rect.width *= hp;
  
  GUI.color = DamageTexture.GetPixelBilinear(hp,0.5f);   //read color value
  GUI.DrawTexture(rect,ForegroundTexture);
  
  GUI.color = Color.white;
  
  
 }

 

CellPickUp()

 public static int powerCell = 0;
 public AudioClip collectSound;
 public Texture2D[] hudcharge;
 public GUITexture chargeHudGUI;
 
 public Texture2D[] meterCharge;
 public Renderer meter;

 
 void CellPickUp(){
 
  HudOn ();
  AudioSource.PlayClipAtPoint(collectSound,transform.position);
  chargeHudGUI.texture = hudcharge[powerCell];
  meter.material.mainTexture= meterCharge[powerCell];
  powerCell++;
  
  if(powerCell == 4)
  {
   Destroy(GameObject.Find("hud_nocharge"),5.0f); //objectname in hirachy
  }
  
 }
 
 void HudOn(){
  if(!chargeHudGUI.enabled)
  {
   chargeHudGUI.enabled = true;
  }
 }

 

 

'유니티3D > 함수' 카테고리의 다른 글

UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07
C# 스크립트 함수 _2  (0) 2013.07.21
C# 스크립트 심화_1  (0) 2013.07.21

Rigidbody.AddForce(Vector3 , Mode) 함수는 리지드 바디에 힘을 줘 움직이기 위한 함수다. 

첫번째 인수에 힘의 방향과 크기를 넣게 되고

두번째 인수에는 힘을 주는 모드를 지정해준다.

비록 같은 힘의 크기와 방향을 줬어도 모드에 따라 다른 움직임이 나오게 되는데

그 모드에 대해서 한번 정리를 해봤다.

 

ForceMode.Force

- 역학적인 개념의 힘을 리지드 바디에 주는 모드다.

짧은 시간에 발생하는 운동량 변화의 크기를 나타내며

주로 바람이나 자기력처럼 연속적으로 주어지는 힘을 나타내는 데 이용 된다.

 

ForceMode.Impulse

- 충격량을 리지드바디에 주는 모드로 충격량이랑 힘의 크기와 주는 시간을 곱한 수치다.

주로 타격이나 폭팔처럼 순간적으로 힘을 나타내는 데 이용된다.

 

ForceMode.Acceleration

- 리지드바디가 갖는 질량을 무시하고 직접적으로 가속량을 주는 모드다.

앞의 두 모드의 경우 질량에 따라 움직임이 달라지지만 이 모드의 경우 질량에 상관 없이 일정한 가속을 만들어 낸다.

주로 지구의 중력 표현에 쓰인다.

 

ForceMode.VelocityChange

- 리지드바디가 가진 질량을 무시하고 직접적으로 속도의 변화를 주는 모드다.

앞서 말한 Acceleration은 시간이 흘러가면서 변화를 일으키는 데 비해 이 모드는 순간적으로 지정한 속도로 변화를 일으킨다.


[출처] Rigidbody.AddForce() 힘 모드 종류에 대해서|작성자 토이박스  [출처] Rigidbody.AddForce() 힘 모드 종류에 대해서|작성자 토이박스

'유니티3D > 함수' 카테고리의 다른 글

UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
C# 스크립트 함수 _2  (0) 2013.07.21
C# 스크립트 심화_1  (0) 2013.07.21

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

유니티3D 스크립팅 개관

http://unity3d.com/support/documentation/ScriptReference/index.html

'유니티3D > 함수' 카테고리의 다른 글

UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07
C# 스크립트 심화_1  (0) 2013.07.21

Scripting Overview

이것은 유니티 안에서 스크립트가 어떻게 작동하는가에 대한 짧은 개관이다.

유니티 내부의 스크립팅은 동작들이라 불리는 스크립트 오브젝트들을 게임 오브젝트들에 접합 시킴으로써 이루어 진다. 스크립트 오브젝트들 내부의 서로 다른 함수들은 어떤 이벤트들 상에서 호출된다. 가장 많이 사용되는 것들은 다음과 같다.

 

 

Update함수:

이 함수는 하나의 프레임이 랜더링되기 전에 호출된다. 여기는 물리 코드를 제외한 대부분의 게임 동작 코드가 실행되는 곳이다.

 

 

FixedUpdate함수:

모든 물리 타입 스텝마다 한번씩 호출된다. 이곳은 물리 기반의 게임 동작들이 실행되는 곳이다.

 

 

함수 외부 코드(Code oputside any function)

오브젝트들이 로드될 때 함수 외부의 코드들이 실행된다. 이것은 스크립트의 상태를 초기화하는데 사용될 수 있다.

주의 : 이 문서의 섹션들은 당신이 Javascript를 사용한다고 가정한다. c#또는 Boo scripts 사용에 관한 것은 Writing scripts in C#을 참조하기 바란다.

당신은 또한 이벤트 핸들러들을 정의할 수 있다. 이 모든 것들은 On으로 시작되는 이름들을 가진다.

(즉 OnCollisionEnter처럼)

미리 정의된 모든 이벤트 리스트를 보려면, MonoBehavior를 위한 문서를 참조하기 바란다.

 

Overview: Common Operations

대부분의 게임 오브젝트에 대한 조작은 게임오브젝트의 Transform, 그리고 Rigidody를 통해서 이루어진다. 이것들은 Behaviour script들 안에서 멤버변수 transform과 rigidbody를 통해 각각 엑세스 될 수 있다.

 

 

그래서 만일 당신이 매 프레임 Y축으로 5도 만큼씩 회전시키길 원한다면 아래와 같이 코드를 작성할 수 있다.

 

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
              transform.Rotate(0,5,0);
 }
}

 

하나의 오브젝트를 앞으로 움직이고 싶다면 다음처럼 쓸 수 있다.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
               transform.Translate(0,0,2);
 }
}

       

Overview: Keeping Track of Time

Time 클래스는 deltaTime이라 불리는 매우 중요한 클래스 변수를 갖는다. 이 변수는 Update 또는 FixedUpdate 함수가 마지막으로 호출된 이후 경과한 시간의 양을 저장한다. (Update함수 내부인지 FixedUpdate함수 내부인지에 따라 다르다.)

 그래서 앞의 예제를 frame rete에 종속되지 않고 일정한 속도로 회전하도록 만들기 위해 다음처럼 수정한다.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
              transform.Rotate( 0, 5 * Time.deltaTime, 0); 

                      }    //end of Update()
}

 

오브젝트 이동

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
              transform.Translate(0, 0, 2 * Time.deltaTime); 

                      }    //end of Update()
}

 

만일 당신이 매 프레임마다 하나의 값에 더하거나 뺀다면 Time.deltaTime으로 곱해야 한다. 당신이 Time.deltaTime을 곱할 때 당신은 " 나는 매프레임 10미터를 움직이는 대신 매초 이 오브젝트를 10미터 움직이길 원한다."라고 표현하는 것이 된다. 이것은 당신의 게임이 Frame rate에 독립적으로 실행될 뿐 아니라 모션을 위해 사용되는 유닛들을 이해하기 쉽게 만들기 때문이다. (초당 10미터)

다른예로, 만일 당신이 시각에 따라 빛의 범위를 증가시키고 싶다면, 다음 구문은 초당 2유닛 만큼씩 반경을 변경시킬것이다.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
             light.range += 2.0F * Time.deltaTime;

                      }    //end of Update()
}

 

Overview: Accessing Other Components

컴포넌트들은 게임오브젝트에 attach된다. 하나의 Renderer 컴포넌트를 게임오브젝트에 attach하는 것은 그것을 스크린 상에 랜더링 되도록 만뜨는 것이고, camara를 attach하는 것은 그것을 카메라 오브젝트 안으로 변환하는 것이다. 모든 스크립트들은 컴포넌트들이므로 그것들은 게임오브젝트들에 attach될 수 있다. 대부분의 일반 컴포넌트들은 간단한 멤버변수들로 엑세스 할 수 있다.

 

 

미리 정의된 변수들의 전체 리스트는 Component, Behavior, 그리고 MonoBehaviour 클래스에 대한 문서들을 참조하기 바란다. 만일 게임오브젝트가 당신의 fetch하고픈 타입의 컴포넌트를 가지고 있지 않다면, 위 변수들은 null로 셋팅될 것이다.

게임오브젝트에 attach된 어떤 컴포넌트나 스크립트는 GetComponent를 통해서 access될 수 있다.

 

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
  
 void Update () {
           OtherScript otherScript = GetComponent<OtherScript>();

           otherScript.DoSomething();

                      }    //end of Update()
}

 

 

 

 

 

 

'유니티3D > 함수' 카테고리의 다른 글

UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07
C# 스크립트 함수 _2  (0) 2013.07.21

+ Recent posts