using UnityEngine; 

using System.Collections; 


public class PlayerCtrl : MonoBehaviour 

    public float velocity = 1.0f; 

    public LayerMask layer; 


    private CharacterController _controller; 


    private bool _isMove = false; 

    private Vector3 _destination = new Vector3(0, 0, 0); 


void Start () 

    { 

        _controller = gameObject.GetComponent<CharacterController>(); 

        _isMove = false; 


void Update () 

    { 


        RaycastHit _hit = new RaycastHit(); 


        //화면을 클릭 하면 땅바닥 좌표 저장. 

        if (Input.GetMouseButton(0)) 

        { 

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 


            if (Physics.Raycast(ray, out _hit, Mathf.Infinity, layer)) 

            { 

                _destination = _hit.point; 

                _isMove = true; 

            } 

        } 


        //땅바닥 좌표가 플레이어와 다르면 움직인다. 

        if (_isMove) 

        { 

            Move(); 

        } 


    //움직이는 함수 

    private void Move() 

    { 

        //목적지와 거리가 같으면 안 움직임 

        if (Vector3.Distance(transform.position, _destination) == 0.0f) 

        { 

            _isMove = false; 

            return; 

        } 


        Vector3 direction = _destination - transform.position; 

        direction = Vector3.Normalize(direction); 


        _controller.Move(direction * Time.deltaTime * velocity); 

    } 

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

UNITY3D 자주쓰는 스크립트_4  (0) 2013.10.08
UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07



RaycastHIt

 //가상 선을 만드는 수. -> 가시적으로


Debug.DrawRay(firePos.transform.position,firePos.transform.forward* 5.0f,Color.green);

RaycastHit hit;

//가상선을 만들어 인식 가능하게 함.

//어디서 , 어느방향으로  ,구조체 hit 을 5 의길이 로...

if(Physics.Raycast(transform.position,transform.forward,out hit,5))

{

//catch the confliction.

if(hit.collider.gameObject.tag == "Door")

{

currentdoor = hit.collider.gameObject;

currentdoor.SendMessage("DoorCheck");

}


GameMenu~!!



using UnityEngine;

using System.Collections;


public class GUIManager : MonoBehaviour {

public AudioClip beep;

public GUISkin manuSkin;

public Rect menuArea;

public Rect PlayBtn;

public Rect InstructBtn;

public Rect quitBtn;

public Rect menuAreaNormalized;

// Use this for initialization

void Start () {

menuAreaNormalized = new Rect(menuArea.x * Screen.width - (menuArea.width*0.5f) ,menuArea.y * Screen.height -(menuArea.height*0.5f) ,menuArea.width ,menuArea.height);

}

// Update is called once per frame

void Update () {

}

void OnGUI()

{

GUI.skin = manuSkin;

GUI.BeginGroup(menuAreaNormalized);

if(GUI.Button(new Rect(PlayBtn),"Iand"))

{

StartCoroutine(ButtonAction("play"));

}

if(GUI.Button(new Rect(InstructBtn),"Instruction"))

{

}

if(GUI.Button(new Rect(quitBtn),"Quit"))

{

StartCoroutine(ButtonAction("quit"));

}

GUI.EndGroup();

}

IEnumerator ButtonAction(string buttonName)

{

audio.PlayOneShot(beep,1.0f);

yield return new WaitForSeconds(1.0f);

if(buttonName=="play")

{

Application.LoadLevel("Game2");

}else if(buttonName == "quit")

{

Application.Quit();

}else{ 

}

}

}

Photon (network)

using UnityEngine;
using System.Collections;

public class PhotonInit : MonoBehaviour {

 
 void Awake(){   //일단 접속.
  PhotonNetwork.ConnectUsingSettings("1.0");
 }
 
 void OnJoinedLobby(){
  Debug.Log ("Joined Lobby");
  PhotonNetwork.JoinRandomRoom();   //아무방이 나접속하라...
 }
 
 void OnCreatedRoom()
 {
  Debug.Log("Enter the room");
 }
 
 void OnJoinedRoom()
 {
  Debug.Log ("OnJoinedRoom");
 }
 
 void OnPhotonRandomJoinFailed()   //접속이 실패하면 이함수가 실행..
 {
  Debug.Log ("There is no room");
  PhotonNetwork.CreateRoom("My room",true,true,10);
 }
 
 void OnGUI()
 {
  GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
 }
}

 

 포 위아래로 콘트롤 하는 소 (mouse scroll)

 using UnityEngine;

using System.Collections;


public class CannonCtrl : MonoBehaviour {

private Transform tr;

private PhotonView pv;


// Use this for initialization

void Awake () {

pv = PhotonView.Get (this);

tr = GetComponent<Transform>();

}

// Update is called once per frame

void Update () { // 포 위아래로 콘트롤 하는소 스 .

if(pv.isMine){

float angle = Time.deltaTime * Input.GetAxis("Mouse ScrollWheel") * 300.0f;

tr.Rotate(angle, 0 ,0);

}

}

}


 TurretCtrl (Raycast 사용)

 using UnityEngine;

using System.Collections;


public class TurretCtrl : MonoBehaviour {

private PhotonView pv;

private Transform tr;

private Quaternion currRot;

// Use this for initialization

void Start () {

tr = GetComponent<Transform>();

pv = PhotonView.Get (this);

pv.observed = this;

Debug.Log(pv.viewID);

Debug.Log(pv.owner);

Debug.Log(pv.isMine);

}

// Update is called once per frame

void Update () {

if(pv.isMine){

Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;

if(Physics.Raycast ( ray, out hit, Mathf.Infinity)){

Vector3 localPos = tr.InverseTransformPoint(hit.point);

float angle = Mathf.Atan2 ( localPos.x, localPos.z) * Mathf.Rad2Deg;

tr.Rotate(0, angle* Time.deltaTime * 2.0f, 0);

}

// Debug.DrawRay(ray.origin, ray.direction * 100.0f, Color.green);

}else{

tr.rotation = Quaternion.Lerp(tr.rotation, currRot, Time.deltaTime);

}

}

void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){

if(stream.isWriting){

stream.SendNext(tr.rotation);

}else{

currRot = (Quaternion) stream.ReceiveNext();

}

}

}


 


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

케릭터 마우스 포인터지점으로 이동  (0) 2013.12.04
UNITY3D 자주쓰는 스크립트_3  (0) 2013.09.29
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07

 

 NeedleRotateCtrl

 public class NeedleRotateCtrl : MonoBehaviour {
 
 
 public Transform gun;
 public Transform pivot;
 
 float prevAngle;
 // Use this for initialization
 void Start () {
       prevAngle = gun.transform.rotation.eulerAngles.z;
 }
 
 // Update is called once per frame
 void Update () {
      float currentAngle = gun.transform.rotation.eulerAngles.z;
      float deltaAngle = currentAngle - prevAngle;
  
  if(deltaAngle != 0)
  {
        transform.RotateAround(pivot.position,Vector3.forward,deltaAngle);
  }
  
  prevAngle = currentAngle;
 }
}

 

 

Time,  rigidbody.AddExplosionForce  

 float startTime;
 float bomLiveTime = 5.0f;
 float bomRadius = 15.0f;
 float bomForce = 1000.0f;

 // Use this for initialization
 void Start () {
         startTime = Time.time;
 }
 
 // Update is called once per frame
 void Update () {
  if((Time.time - startTime) > bomLiveTime)
  {
   Bom();
  }
 }
 
 void OnCollisionEnter(Collision Col)
 {
  Bom (); 
 }
 
 void Bom()
 {
  Collider[] collider = Physics.OverlapSphere(transform.position,bomRadius);
  
  foreach(Collider col in collider)
  {
   if(!col.gameObject.Equals(gameObject) && col.rigidbody != null)
   {
    rigidbody.AddExplosionForce             

                             (bomForce,transform.position,bomRadius,5.0f);
   }
  }
  
  Destroy(gameObject);
 }

 

 외부 스크립트 사용하기

public RocketShoot rocketshoot;



rocketshoot = GameObject.Find("RocketShoot").GetComponent<RocketShoot>();



rocketshoot.fire();


RocketShoot ---> 오브젝트 이름
RocketShoot ---> 스크립트 이름

 

transform.FindChild("door").SendMessage("DoorCheck");

//transform -> 경로명을 포함한다.

 

 

 

 

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

케릭터 마우스 포인터지점으로 이동  (0) 2013.12.04
UNITY3D 자주쓰는 스크립트_4  (0) 2013.10.08
UNITY3D 자주쓰는 스크립트_2  (0) 2013.09.27
UNITY3D 자주쓰는 스크립트_1  (0) 2013.09.27
Rigidbody.AddForce()  (0) 2013.08.07

 

네비게이션, GetComponent, Animation, BloodEffect, BloodPanel, SetBool

 using UnityEngine;
using System.Collections;

[RequireComponent (typeof(AudioSource))]     //i don't need to Input Audio sources again in component.
public class MonsterCtrl : MonoBehaviour {
 
 public Transform PlayerTr;
 public Transform MonsterTr;
 public NavMeshAgent nv;
 public float TraceTime = 0.5f;
 public Animator anim;
 public int hp = 100;
 public AudioClip killSound;
 bool isdead = false;
 private int hitID;
 public GameObject BloodEffect;
 public GameObject BloodPanel;
 
 // Use this for initialization01037141701
 void Start () {
  PlayerTr = GameObject.Find ("Player").GetComponent<Transform>();
  MonsterTr = this.gameObject.GetComponent<Transform>();
  nv = GetComponent<NavMeshAgent>();
  nv.destination = PlayerTr.position;   //start to trace where player's position.
  anim = GetComponent<Animator>();
  hitID = Animator.StringToHash ("Base.gothit");   //char -> num..
  //01051464472
 }
 
 // Update is called once per frame
 void Update () {
  if(isdead) return;  //if monster is dead , exit Update()!!
  
  if(anim.IsInTransition (0) && anim.GetNextAnimatorStateInfo(0).nameHash == hitID)
  {
   nv.Resume();
   anim.SetBool("IsHit",false);
  }
  
  if(Vector3.Distance(MonsterTr.position,PlayerTr.position) < 2.0f)
  {
   nv.Stop();//stop trace~!!!!
   anim.SetBool("IsAttack",true);
   anim.SetBool("IsTrace",false);
  }else
  {
   if(Time.time > TraceTime)
   {
    nv.destination = PlayerTr.position;
    TraceTime = Time.time + 0.5f;
   }
   
   nv.Resume();   //restart to trace~!!!!
   anim.SetBool("IsAttack",false); 
   anim.SetBool("IsTrace",true);
   
  }
 }
 
 
 
 //catch conflict
 void OnCollisionEnter(Collision col)  //col is bullet
 {
  if(col.gameObject.tag == "Bullet" &&  !isdead)
  {
   nv.Stop();
   anim.SetBool("IsHit",true);
   
   StartCoroutine(this.CreateBlood(MonsterTr.position));   //make Blood effet
   StartCoroutine(this.CreateBloodPanel(MonsterTr.position));  //make Blood Panel
   
   hp -= col.gameObject.GetComponent<Bullet>().damage;    //how to use other's class variable.
   Destroy(col.gameObject);
   if(hp <= 0)
   {
          audio.PlayOneShot(killSound,1.0f);   //(sound name, volume)
           nv.Stop();
           anim.SetBool("IsDead",true);
    isdead = true;
    this.gameObject.GetComponent<CapsuleCollider>().enabled = false;
    
    Destroy(gameObject,3.0f);
   }
  }
  
 }//end of OnCollisionEnter
 
 
  IEnumerator CreateBlood(Vector3 pos)
  {
    GameObject newBlood = (GameObject)Instantiate(BloodEffect,pos,Quaternion.identity);
    Destroy(newBlood,0.3f);
  
    yield return null;
  }
 
 
  IEnumerator CreateBloodPanel(Vector3 pos)   // position value
  {
    Quaternion rotate = Quaternion.Euler(0,Random.Range(0,360),0); //valuable Blood effects   
    GameObject newBloodPanel = (GameObject)Instantiate(BloodPanel,pos,rotate);
    Destroy(newBloodPanel,3.0f);
  
    yield return null;
   
  }
  
  public void YouWin()
  {
   nv.Stop();
   isdead = true;
   anim.SetBool("IsGameOver",true);
  }

}

 

 

Button_1

 void OnGUI()
 {
    
      Rect rect2 = new Rect(Screen.width/2-50,Screen.height/2,100,25);
      if(GUI.Button(rect2,"처음으로"))
  {
       Application.LoadLevel("Title");
  }
  
      Rect rect3 = new Rect(Screen.width/2-50,Screen.height/2+30,100,25);
      if(GUI.Button(rect3,"게임종료"))
  {
        Application.Quit();
        Debug.Log("Quit");
  }
 }

 

Button_2

 public Texture2D nomalTexture;
 public Texture2D rollOverTexture;
 public AudioClip beep;
 public bool quitButton = false;

 void OnMouseExit()
 {
  guiTexture.texture = nomalTexture;
 }
 
 IEnumerator OnMouseUp()
 {
  audio.PlayOneShot(beep);
  yield return new WaitForSeconds(0.35f);
  if(quitButton)
  {
   Application.Quit();
   Debug.Log("quit");
  }else
  {
   Application.LoadLevel("Title");
  }
 }

 

 

 

 

 

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

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

+ Recent posts