반응형

 

방법 1.

// 가로 , 세로 값 지정해서 Resize하기
    private Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
    {
        Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
        Color[] rpixels = result.GetPixels(0);
        float incX = (1.0f / (float)targetWidth);
        float incY = (1.0f / (float)targetHeight);
        for (int px = 0; px < rpixels.Length; px++)
        {
            rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
        }
        result.SetPixels(rpixels, 0);
        result.Apply();
        return result;
    }

 

 

 

 

 

 

방법 2.
    // 비율로 해서 Resize하기
    public  Texture2D ScaleTexture( Texture2D source, float _scaleFactor)
    {
        if (_scaleFactor == 1f)
        {
            return source;
        }
        else if (_scaleFactor == 0f)
        {
            return Texture2D.blackTexture;
        }

        int _newWidth = Mathf.RoundToInt(source.width * _scaleFactor);
        int _newHeight = Mathf.RoundToInt(source.height * _scaleFactor);


        
        Color[] _scaledTexPixels = new Color[_newWidth * _newHeight];

        for (int _yCord = 0; _yCord < _newHeight; _yCord++)
        {
            float _vCord = _yCord / (_newHeight * 1f);
            int _scanLineIndex = _yCord * _newWidth;

            for (int _xCord = 0; _xCord < _newWidth; _xCord++)
            {
                float _uCord = _xCord / (_newWidth * 1f);

                _scaledTexPixels[_scanLineIndex + _xCord] = source.GetPixelBilinear(_uCord, _vCord);
            }
        }

        // Create Scaled Texture
        Texture2D result = new Texture2D(_newWidth, _newHeight, source.format, false);
        result.SetPixels(_scaledTexPixels, 0);
        result.Apply();

        return result;
    }

반응형
반응형

* 간단 요약

카메라 두대로 culling mask 이용하여 자연스러운 흔들기 연출 하겟습니다.

카메라 두대중 mainCamera 는 플레이어만 보이게하고,

subCamera 는 플레이어 제외하고 모든 오브젝트 보이게 합니다.

그리고 총쏠때(흔들 시점에) subCamera를 x,y 축위치를 랜덤으로 변경하여 흔들기를 해줍니다.

 

 

 

 

 

- 두카메라를 부모오브젝트에 상속

    CamAxis

     └ Main Camera

     └ Sub Camera

 

 

- 메인 카메라에 플레이어만 Culling mask 지정 

  Clear flags 는 Skybox로 

 

 

 

 

 

-서브 카메라는 Player 제외하고 모든 레이어 지정

 

 

 

 

- 플레이어 오브젝트에 레이어 지정 (플레이어 의 하부 오브젝트까지 지정해줍니다 )

 

 

 

 

 

 

-메인카메라로 확인하시면 플레이어만 보이는것을 확인할수 잇다.

 

 

 

 

- 서브카메라 보면 플레이어 제외하고 모든 오브젝트를 보이는것이 확인이 된다.

 

 

 

- 두카메라가 다같이 표현되어 플레이어와 모든 오브젝트가 보이는것을 확인 할수잇다.

 

 

 

 

 

 

 

 

 

- 이제 총을쏠때 흔들기를 하자

  카메라 부모오브젝트 (CamAxis) 에 아래 스크립트를 넣자

 

  기본적으로 CamAxis 는 Player스크립트에서 Update로  마우스 위치값을 받아 상하좌우 움직임을 하고 잇다.

이 상태에서 총쏠때  마다 Set_Shaking(일정수치) 호출해준다

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//마우스 움직임 따라 메인캠 부모 Trasform이 움직인다 =>Player.cs Update() 함수에서 호출 된다
 public void FollowCamToTarget(Vector3 targetPosition)
  {
        //메인캠의 부모Tr pos는 마우스 포인터따라 움직인다
        CameraAxis.localPosition = targetPosition;
        CamOrinPos = targetPosition;
 
        //서브캠이 흔들린다
        SubCameraTransform.localPosition = ShakeVector;
  }
 
 
    Vector3 ShakeVector = new Vector3();
    float ShakeCameraForce = 0f;
    float ShakeCameraSpeed = 0f;
    Vector3 CamOrinPos = Vector3.zero;
    public void Set_Shaking(float shakeForce) //총 한번 쏠때마다 이 함수가 호출된다
    {
 
        // 흔들림 값 할당
        ShakeCameraForce = shakeForce;
        //흔들림 속도 할당
        ShakeCameraSpeed = ShakeCameraForce / 2;
        // 흔들기 시작
        StartCoroutine(Co_Shake());
    }
 
   
   
    //카메라 흔들기 동작
    IEnumerator Co_Shake()
    {
        while(ShakeCameraForce > 0f)
        {
            float shaking = 0.04f * ShakeCameraForce;
 
// x, y 축 움직일 랜덤값
            float xrand = Random.Range(-shaking, shaking);
            float yrand = Random.Range(0, shaking);
            ShakeVector = new Vector3(xrand, yrand, 0);
 
 
            ShakeCameraForce -= Time.deltaTime * 10f * ShakeCameraSpeed;
            
            yield return null;
        }
 
        //동작 완료후 제자리로 
        ShakeVector = Vector3.zero;
       // 서브캠 제자리로 
        SubCameraTransform.localPosition = ShakeVector;
    }
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs
 
 
 

 

 

 

 

 

 

* 카메라 두대로 사용하여 아래 첫 움짤 처럼 보이게 된다. 

 

* 카메라 한대로 사용하여 두번쨰 움짤을 보게 되면, 플레이어만 흔들리는 것처럼 보일것이다.

  이런 이유로 두대로 CullingMask를 사용하여 플레이어는 흔들리것이 보이지 않게 연출 한것이다.

 

 

* 각 카메라가 중첩되지 않은 Layer를 선택해서 렌더링 시키고 있기때문에 Batch, SetPassCall 에는 커지는 영향이 없다.카메라 한대쓰는것이랑 같다.

 

 

 

 

 

 #카메라 두대 사용하여 연출햇을떄

 

 

 

 

 

 

# 카메라한대로 카메라 흔들기 했을때

 

 

반응형
반응형

 

사용 방법입니다.

 

우선 각 enum에 의미는

 

 RigidbodyConstraints.FreezeRotationX  //X회전 프리즌(회전하지않기)

RigidbodyConstraints.FreezeRotationY  //Y회전 프리즌(회전하지않기)

RigidbodyConstraints.FreezeRotationZ //Z회전 프리즌

RigidbodyConstraints.FreezePositionX //X위치 프리즌 (X축이동 하지않기)

RigidbodyConstraints.FreezePositionY //Y위치 프리즌 (Y축이동 하지않기)

RigidbodyConstraints.FreezePositionZ //Z위치 프리즌 (Z축이동 하지않기)

 

 

 

코드로 제어 하실때는 

 

  rigid.constraints = RigidbodyConstraints.FreezeRotationX ; 

만약 여러게 제어를 넣고 싶으면 

  rigid.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY ;

 

 

 

아래 예제입니다.


            if (rigid == null)
            {
                //리지바디 추가
                rigid = tr.gameObject.AddComponent();
                rigid.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY |
                    RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ;
            }

반응형
반응형

NavMeshAgent.SetDestination 호출후 같은 프레임에 네비는 바로 적용이 되지 않습니다.

 

SetDestination 호출후 목적지 계산이 필요하므로  네비 계산이 완료 되면 다음 프레임에 목적지 이동 하기 시작합니다.

 

 

위와 같은 확인은 같은 프레임에서 NavMeshAgent.SetDestination 호출후 NavMeshAgent.remainDistance를 확인해 보면 값이 0 인걸 알수 잇습니다.

 

다음 프레임 쯔음에 다시 NavMeshAgent.remainDistance 확인해 보면 목적지까지의 현재 거리를 나타납니다 ,

이떄 네비가 계산완료하여 움직입니다.

 

 

그래서 NavMeshAgent.SetDestination 호출후 바로 네비가 적용되지 않으니

네비가 계산완료 할떄까지 기달려야합니다. 

 

NavMeshAgent 는 계산이 완료 되엇다는  프로퍼티를 제공하니 (NavMeshAgent.pathPending) 활용하면 좋을거 같습니다 .

 

유니티 레퍼런스에 의하면 NavMeshAgent.pathPending 는

"계산중이지만 아직 준비가 되지 않는 경로(path)를 나타냅니다." 라고 설명되어있습니다.

그래서 pathPending  가 false 이면 계산완료 햇다는 것입니다.

 

 

 

ex) NavMeshAgent.pathPending 사용 예 

void Update()

{

   if(!NavMeshAgent.pathPending)

   {

      //계산 완료하였으니 이제 목적지까지 이동하기 시작한다.

   }

}

반응형
반응형

Rigidbody.Addforce 사용할 오브젝트가 Rigidbody.Addforce함수를 여러번 사용할시 

Rigidbody.Addforce햇었던 값이 합해서 적용이 됩니다. 

 

ex)

처음에 Addforce(new vector3(0,0,1) * 100f); 호출후 바로 
Addforce(new vector3(0,1,0)*100f); 호출하면 vector3(0,1,0) 방향으로 나갈줄 알앗는데 

vector3(0,1,0) + vector3(0,0,1)  = vector3(0,1,1) 방향으로 나가더군요 ....

왜 함수 이름이 Addforce 인줄 알게 되엇답니다. 흠흠

 

그래서 이전 addForce 주웟던 것을 초기화 하려면 

 

 Rigidbody.velocity = vector3.zero; 
 Rigidbody.angularVelocity = vector3.zero; ( addTorque 사용시)

 

하시면 초기화됩니다.

 

 

 

이상입니다~

반응형
반응형

코루틴 시작시 StartCouroutine() 소량의 가비지가 쌓인다 
또한 yield 구문에서 불필요한 힙할당으로 가비지가 쌓이는경우가 있습니다.

아래 예입니다



1. yield return 0; 

   0 의값은 변수가 박싱처리되기 떄문에 박싱시 가비지를 생성하게됩니다

   그래서 yiedl return null 사용하는게 좋다


2. yield return new waitfForSeconds(1f);

아래 경우 반복문을 돌때마다 waitfForSeconds 를 생성하고 삭제하기떄문에 가비지가 생성됩니다.


 IEnumerator co_ChkDieTargetPlayer()

{

        while (true)

        {

yield return new waitfForSeconds(1f);

         }

}



2 경우 개선 

WaitForSeconds waitfor = new WaitForSeconds(1f);

IEnumerator co_ChkDieTargetPlayer()

{

        while (true)

        {

yield return waitfor ;

         }

}



반응형
반응형

OntriggerStay() 함수 사용시 주의 해야할점

tag 문자열 비교시 compareTag() 함수를 이용해서 비교 해라 그러지 않으면 OntriggerStay 함수 호출시 마다 가비지 컬렉터가 쌓이게 되어 
게임 부하를줄수 잇다.




나쁜 예)

public void OnTriggerEnter(Collider coll)

    {

        if (coll.tag == "Player")

        {

           

        }

    }



좋은 예)

public void OnTriggerEnter(Collider coll)

    {

        if (coll.CompareTag(playerTag))

        {

           

        }

    }






- 나쁜예 사용시 가비지가 쌓이는 증거 

 파란색 부분 GCAlloc 에 10KB 정보 GC가 쌓인것을 확인할수 잇다.




- 좋은예의 가비지가 쌓이지 않는 증거

GC Alloc 에 0B 이다.






반응형
반응형


유니티 에서 보통 WWW 클래스를 통해 웹통신을 하엿는데 2017 버전부터 WWW를 대체할 UnityWebRequest  클래스가 등장햇습니다.

2018 에서는 아예 UnityWebRequest 를 권장하고 있습니다.

WWW 클래스가 나중에는 쓰여지질 않을텐데요 이에 UnityWebRequest  예제를 만들어 보앗습니다.



예제 1.








예제 2.



반응형

+ Recent posts