Get it on Google Play


Wm뮤 :: 'Unity' 카테고리의 글 목록 (13 Page)

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
전자과 게임프로그래머 (퇴사함)
2022.3.22f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2021. 7. 1. 01:41 Unity/C#

 

각도계산

https://wmmu.tistory.com/entry/%EC%9C%A0%EB%8B%88%ED%8B%B0-%EB%B0%A9%ED%96%A5%EA%B4%80%EB%A0%A8-%ED%95%A8%EC%88%98-%EC%A0%95%EB%A6%AC

 

결과값이 각도일 경우에는 위 링크로

결과값이 좌표일 경우에는 이 글을 이용

 

 

 

 

 

LenPos

각도를 좌표로

Quaternion direction;
Vecter3 distance;
LenPos = direction * Vector3.forward * distance

 

 

유니티판 PointDirection

2D 계산용

Debug.Log(Quaternion.Euler(0, 0, 0) * Vector2.right); //(1, 0, 0)
Debug.Log(Quaternion.Euler(0, 0, 90) * Vector2.right); //(0, 1, 0)
Debug.Log(Quaternion.Euler(0, 0, 180) * Vector2.right); //(-1, 0, 0)
Debug.Log(Quaternion.Euler(0, 0, 270) * Vector2.right); //(0, -1, 0)

 

 

 

ScreenToRectPosition

var canvas = GetComponentInParent<Canvas>();
Camera cam = null;
switch (canvas.renderMode)
{
    case RenderMode.ScreenSpaceOverlay:
        break;
    case RenderMode.ScreenSpaceCamera:
    case RenderMode.WorldSpace:
        cam = canvas.worldCamera;
        break;
    default:
        break;
}
if (cam == null)
{
    cam = Camera.main;
}



switch (canvas.renderMode)
{
    case RenderMode.ScreenSpaceOverlay:
        handle.transform.position = eventData.position;
        break;
    case RenderMode.ScreenSpaceCamera:
    case RenderMode.WorldSpace:
        Vector3 rectPos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<RectTransform>(), eventData.position, cam, out rectPos);
        handle.transform.position = rectPos;
        break;
    default:
        break;
}

 

위에서 카메라만 가져올땐 약식으로 이거 써도 된다

public (Canvas, Camera) GetCanvasCamera()
{
    var canvas = GetComponentInParent<Canvas>();
    var camera = canvas.worldCamera;
    if (camera == null)
    {
        camera = Camera.main;
    }
    return (canvas,camera);

}

 

 

 

 

 

 

 

 

 

특정 각도를 upVector삼아서 회전

(노란색 : 회전시킨 벡터)

(빨간색 : 기준각도)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;




public class VectorRotationTest : MonoBehaviour
{
    void OnDrawGizmos()
    {
        //입력값
        var axis = new Vector3(-2.85f, 1.4f, 3.4f);
        var a = transform.rotation;
        var b = Quaternion.Euler( 0,  0, (Time.time * 30) % 360);



        //노란색원의 좌표계
        var radius = Vector2.Distance(Vector2.zero, new Vector2(axis.x, axis.y));
        var center = transform.position + a * Vector3.forward * axis.z;
        UnityEngine.Debug.DrawLine(center, center + a * Vector3.up * radius, Color.blue);
        UnityEngine.Debug.DrawLine(center, center + a * Vector3.right * radius, Color.green);

        //노란색원
        UnityEditor.Handles.color = Color.yellow;
        UnityEditor.Handles.DrawWireDisc(center, a * Vector3.forward, radius);
        UnityEditor.Handles.color = Color.white;


        //흰색원과 좌표계
        UnityEngine.Debug.DrawLine(transform.position, center, Color.red);
        UnityEngine.Debug.DrawLine(transform.position, transform.position + a * Vector3.up, Color.blue);
        UnityEngine.Debug.DrawLine(transform.position, transform.position + a * Vector3.right, Color.green);
        UnityEditor.Handles.DrawWireDisc(transform.position, a * Vector3.forward, 1f);

        var upRotation = a;

        //핵심
        UnityEngine.Debug.DrawLine(transform.position, transform.position + upRotation * b * axis, Color.yellow);

        //검은색 선
        UnityEngine.Debug.DrawLine(transform.position, transform.position + upRotation * b * Quaternion.Euler(0, 0, 90) * axis, Color.black);
        UnityEngine.Debug.DrawLine(transform.position, transform.position + upRotation * b * Quaternion.Euler(0, 0, 180) * axis, Color.black);
        UnityEngine.Debug.DrawLine(transform.position, transform.position + upRotation * b * Quaternion.Euler(0, 0, 270) * axis, Color.black);





    }
}

 

 

 

 

 

벡터를 6방향으로 정규화

var axisNormal=vector;
if (Mathf.Abs(axisNormal.x) > Mathf.Abs(axisNormal.y))
{
    axisNormal.y = 0;
}
if (Mathf.Abs(axisNormal.x) > Mathf.Abs(axisNormal.z))
{
    axisNormal.z = 0;
}
else
{
    axisNormal.x = 0;
}
axisNormal = axisNormal.normalized;

 

 

 

GPT가 짜준 패스에서 최단지점 구하는 함수

Vector3 ClosestPoint(Vector3 a, Vector3 b, Vector3 position)
{
    Vector3 ab = b - a;
    Vector3 ap = position - a;
    float t = Vector3.Dot(ap, ab) / Vector3.Dot(ab, ab);
    t = Mathf.Clamp01(t); // a와 b 사이의 지점만을 고려하려면 이 줄을 추가합니다.
    return a + ab * t;
}
Vector3 ClosestPoint(Vector3 position)
{
    var path = GetPath();
    float minDistance = float.MaxValue;
    Vector3 closestPoint = Vector3.zero;

    for (int i = 0; i < path.Count - 1; i++)
    {
        Vector3 point = ClosestPoint(path[i], path[i + 1], position);
        float distance = Vector3.Distance(point, position);

        if (distance < minDistance)
        {
            minDistance = distance;
            closestPoint = point;
        }
    }

    return closestPoint;
}

List<Vector3> GetPath()
{
    var childs = new List<Transform>();
    for (int i = 0; i < tracksParent.childCount; i++)
    {
        childs.Add(tracksParent.GetChild(i));
    }
    var path = childs.ConvertAll(x => x.position);

    return path;
}

 

 

상대좌표

그러니까 글로벌 좌표를 로컬 좌표로 바꿔준다

v1

더보기


스케일값은 계산되어있지 않다

var localPosition = Quaternion.Inverse(transform.rotation) * (globalPosition - transform.position);

 

 

역변환 포함

v2


var globalPosition = transform.TransformPoint(localPosition);
var localPosition = transform.InverseTransformPoint(globalPosition);



 

벡터를 특정 각도로 랜덤하게 회전

FPS 게임에서 총알 각도등을 계산할때 쓴다

기존에 내가 계산하던 방식

var vector = Camera.main.transform.forward;
var angle = 5f;
var randomAngle = Random.Range(0, angle);
var rotatedVector = Quaternion.LookRotation(vector, Vector3.up) * Quaternion.Euler(0, 0, Random.Range(0f, 360f)) * Quaternion.Euler(randomAngle, 0, 0) * Vector3.forward * Vector3.Distance(Vector3.zero, vector);

Debug.DrawRay(Camera.main.transform.position, rotatedVector, Color.black);

 

AI가 짜준 방식

이쪽이 더 효율적이다. 위에건 사람이 작동원리를 알기 쉬우니 그냥 둠. 다른 게임엔진에서 쓸수도 있고

var vector = Camera.main.transform.forward;
var angle = 5f;
var randomAngle = Random.Range(0, angle);
var rotatedVector = Quaternion.AngleAxis(randomAngle, Random.onUnitSphere) * vector;

Debug.DrawRay(Camera.main.transform.position, rotatedVector, Color.black);

 

 

WorldPosition을 ScreenPosition으로

var cam = Camera.main;
var screenPoint = RectTransformUtility.WorldToScreenPoint(cam, worldPosition);

 

 

그리고 하기는 예제이다

 

https://wmmu.tistory.com/search/WorldToScreenPoint

 

Wm뮤

자료정리용 개인공간

wmmu.tistory.com

 

 

WorldPosition, ScreenPosition, localRectPosion 종합세트

 

v1

더보기
#if UNITY_EDITOR
    public GameObject handle;
    void OnDrawGizmos()
    {


        // Draw a semitransparent blue cube at the transforms position
        var rectTransform = GetComponent<RectTransform>();
        if (rectTransform == null)
        {
            return;
        }
        var lossyScale = rectTransform.lossyScale;
        float wid = rectTransform.rect.width;
        float hei = rectTransform.rect.height;
        var pivot = rectTransform.pivot;

        Vector3 downPos = transform.up * lossyScale.y * hei * (pivot.y - 1);
        Vector3 upPos = transform.up * lossyScale.y * hei * pivot.y;
        Vector3 leftPos = transform.right * lossyScale.x * wid * (pivot.x - 1);
        Vector3 rightPos = transform.right * lossyScale.x * wid * pivot.x;

        Gizmos.color = Color.white;

        //꼭지점 추출
        var worldPositions = new Vector3[4];
        worldPositions[0] = transform.position + upPos + leftPos;
        worldPositions[1] = transform.position + upPos + rightPos;
        worldPositions[2] = transform.position + downPos + leftPos;
        worldPositions[3] = transform.position + downPos + rightPos;

        var worldHandlePosition = handle.transform.position;
        Gizmos.DrawLine(worldPositions[0], worldPositions[1]);
        Gizmos.DrawLine(worldPositions[2], worldPositions[3]);
        Gizmos.DrawLine(worldPositions[0], worldPositions[2]);
        Gizmos.DrawLine(worldPositions[1], worldPositions[3]);



        //worldPosition 2 screenPosition
        Vector2[] screenPositions;
        Vector2 screenHandlePosition;
        {

            var canvas = GetComponentInParent<Canvas>();
            Camera cam = null;
            switch (canvas.renderMode)
            {
                case RenderMode.ScreenSpaceOverlay:
                    break;
                case RenderMode.ScreenSpaceCamera:
                case RenderMode.WorldSpace:
                    cam = canvas.worldCamera;
                    break;
                default:
                    break;
            }
            if (cam == null)
            {
                cam = Camera.main;
            }

            screenPositions = System.Array.ConvertAll(worldPositions, wp => RectTransformUtility.WorldToScreenPoint(cam, wp));
            screenHandlePosition = RectTransformUtility.WorldToScreenPoint(cam, worldHandlePosition);

            for (int i = 0; i < 4; i++)
            {
                var color = Color.white;
                if (i < 2)
                {
                    color = Color.black;
                }
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldPositions[i], $"wp[{i}] : {worldPositions[i].ToString("F2")}\nsp[{i}] : {screenPositions[i]}", guiStyle);
            }
        }




        //worldPosition 2 normalizedPosionLocal
        Vector2 localRectHandlePosion;
        {
            var l = (Quaternion.Inverse(transform.rotation) * (transform.position + leftPos)).x;
            var r = (Quaternion.Inverse(transform.rotation) * (transform.position + rightPos)).x;
            var t = (Quaternion.Inverse(transform.rotation) * (transform.position + upPos)).y;
            var d = (Quaternion.Inverse(transform.rotation) * (transform.position + downPos)).y;



            localRectHandlePosion = Quaternion.Inverse(transform.rotation) * worldHandlePosition;
            localRectHandlePosion.x = (localRectHandlePosion.x - l) / (r - l);
            localRectHandlePosion.y = (localRectHandlePosion.y - d) / (t - d);


            {
                var color = Color.green;
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldHandlePosition, $"whp : {worldHandlePosition.ToString("F2")}\nshp : {screenHandlePosition}\nlrhp : {localRectHandlePosion.ToString("F2")}", guiStyle);
            }
        }

        //localRectHandlePosion 2 worldPosition
        {
            var l = (Quaternion.Inverse(transform.rotation) * (transform.position + leftPos)).x;
            var r = (Quaternion.Inverse(transform.rotation) * (transform.position + rightPos)).x;
            var t = (Quaternion.Inverse(transform.rotation) * (transform.position + upPos)).y;
            var d = (Quaternion.Inverse(transform.rotation) * (transform.position + downPos)).y;


            var worldPos = transform.rotation * new Vector3(l + localRectHandlePosion.x * (r - l), d + localRectHandlePosion.y * (t - d), 0);


            {
                var color = Color.gray;
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldPos, "\n\n\nworldPos", guiStyle);
            }
        }

    }
#endif

 

 

v2


#if UNITY_EDITOR
    public GameObject handle;
    void OnDrawGizmos()
    {


        // Draw a semitransparent blue cube at the transforms position
        var rectTransform = GetComponent<RectTransform>();
        if (rectTransform == null)
        {
            return;
        }
        var lossyScale = rectTransform.lossyScale;
        float wid = rectTransform.rect.width;
        float hei = rectTransform.rect.height;
        var pivot = rectTransform.pivot;

        Vector3 downPos = transform.up * lossyScale.y * hei * (pivot.y - 1);
        Vector3 upPos = transform.up * lossyScale.y * hei * pivot.y;
        Vector3 leftPos = transform.right * lossyScale.x * wid * (pivot.x - 1);
        Vector3 rightPos = transform.right * lossyScale.x * wid * pivot.x;

        Gizmos.color = Color.white;

        //꼭지점 추출
        var worldPositions = new Vector3[4];
        worldPositions[0] = transform.position + upPos + leftPos;
        worldPositions[1] = transform.position + upPos + rightPos;
        worldPositions[2] = transform.position + downPos + leftPos;
        worldPositions[3] = transform.position + downPos + rightPos;

        var worldHandlePosition= handle.transform.position;
        Gizmos.DrawLine(worldPositions[0], worldPositions[1]);
        Gizmos.DrawLine(worldPositions[2], worldPositions[3]);
        Gizmos.DrawLine(worldPositions[0], worldPositions[2]);
        Gizmos.DrawLine(worldPositions[1], worldPositions[3]);



        //worldPosition 2 screenPosition
        Vector2[] screenPositions;
        Vector2 screenHandlePosition;
        {

            var canvas = GetComponentInParent<Canvas>();
            Camera cam = null;
            switch (canvas.renderMode)
            {
                case RenderMode.ScreenSpaceOverlay:
                    break;
                case RenderMode.ScreenSpaceCamera:
                case RenderMode.WorldSpace:
                    cam = canvas.worldCamera;
                    break;
                default:
                    break;
            }
            if (cam == null)
            {
                cam = Camera.main;
            }

            screenPositions = System.Array.ConvertAll(worldPositions, wp => RectTransformUtility.WorldToScreenPoint(cam, wp));
            screenHandlePosition = RectTransformUtility.WorldToScreenPoint(cam, worldHandlePosition);

            for (int i = 0; i < 4; i++)
            {
                var color = Color.white;
                if (i < 2)
                {
                    color = Color.black;
                }
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldPositions[i], $"wp[{i}] : {worldPositions[i].ToString("F2")}\nsp[{i}] : {screenPositions[i]}", guiStyle);
            }
        }




        //worldPosition 2 normalizedPosionLocal
        Vector2 normalizedPositionLocal;
        {
            Vector2 localHandlePoint = rectTransform.InverseTransformPoint(worldHandlePosition);

            normalizedPositionLocal = (localHandlePoint- rectTransform.rect.min)/ rectTransform.rect.size;


            {
                var color = Color.green;
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldHandlePosition, $"whp : {worldHandlePosition.ToString("F2")}\nshp : {screenHandlePosition}\nlhp : {normalizedPositionLocal.ToString("F2")}", guiStyle);
            }
        }

        //normalizedPosionLocal 2 worldPosition
        {
            var rect = rectTransform.rect;
            var  worldPos = transform.TransformPoint(rect.min + normalizedPositionLocal * rect.size);


            {
                var color = Color.gray;
                var guiStyle = new GUIStyle();
                guiStyle.fontSize = 16;
                guiStyle.normal.textColor = color;
                UnityEditor.Handles.Label(worldPos, "\n\n\nworldPos", guiStyle);
            }
        }

    }
#endif

 

 

 

 

 

 

 

씬뷰상 오브젝트 거리

아바타툴 만들때 사용함

var screenPoint = HandleUtility.WorldToGUIPoint( transform.position);
targets = targets.OrderBy(target => Vector2.Distance(HandleUtility.WorldToGUIPoint(target.transform.position), screenPoint)).ToArray();

 

 

 

 

 

 

 

 

 

'Unity > C#' 카테고리의 다른 글

유니티 빌드 관련 코드  (0) 2021.08.09
유니티 커스텀 인터페이스  (0) 2021.06.24
유니티 기즈모 (Gizmo) 관련코드  (0) 2021.06.15
posted by 모카쨩
2021. 6. 24. 18:23 Unity/C#

 

 

 

 

드래그 체크

using System.Collections;
using System.Collections.Generic;
using UnityEngine;



using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CustomInteface : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public GameObject ui;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void OnBeginDrag(PointerEventData data)
    {
    }



    public void OnDrag(PointerEventData data)
    {
    }




    public void OnEndDrag(PointerEventData data)
    {
        var zPos = transform.position.z;

        var pos = Camera.main.ScreenToWorldPoint(data.position);
        pos.z = zPos;


        var pressPos = Camera.main.ScreenToWorldPoint(data.pressPosition);
        pressPos.z = zPos;




        ui.transform.position = pos;
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

아이템 드래그

        if (Vector2.Distance(eventData.pressPosition,eventData.position)>300)
        {
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<RectTransform>(), eventData.position, eventData.pressEventCamera, out var worldPoint))
            {
                transform.position = worldPoint;
            }
        }
        else
        {
            transform.position = eventData.pressPosition;
        }

 

'Unity > C#' 카테고리의 다른 글

유니티 좌표계산 모음  (0) 2021.07.01
유니티 기즈모 (Gizmo) 관련코드  (0) 2021.06.15
유니티 안드로이드 빌드관련 스크립트  (0) 2021.06.10
posted by 모카쨩
2021. 6. 22. 17:51 Unity

 

 



void Start()
{
}
void OnGUI()
{
}
/*
void OnLevelWasLoaded()
{
	//씬이동시 발생(레거시 코드)
}
*/
void Update()
{
	//매프레임 발생
}
void OnTriggerEnter(Collider other)
{
	//트리거 콜라이더 충돌시 발생
}

 

 

씬이동시 발생

    void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode)
    {
        AssetUnLoad();
    }
    void Start()
    {
        UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
    }

'Unity' 카테고리의 다른 글

LogError 뜰때마다 pause 되는현상 수정  (0) 2021.09.24
유니티 VR 세팅관련  (0) 2021.05.15
오큘러스 컴포넌트 및 프리팹  (0) 2021.05.15
posted by 모카쨩
2021. 6. 15. 13:12 Unity/C#

 

 

구를그림

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }

 

가려지지 않는 구를 그림

    void OnDrawGizmos()
    {
#if UNITY_EDITOR
        UnityEditor.Handles.DrawWireDisc(transform.position, transform.up, radius);
        UnityEditor.Handles.DrawWireDisc(transform.position, transform.right, radius);
        UnityEditor.Handles.DrawWireDisc(transform.position, transform.forward, radius);
#endif
    }

 

 

원을 그림

void OnDrawGizmos()
{
    UnityEditor.Handles.DrawWireDisc(transforms[i].position, fowordAngle * Vector3.up, radius);
}

 

텍스트 표시

#if UNITY_EDITOR
        void OnDrawGizmos()
        {
            UnityEditor.Handles.Label(transform.position, "text");
        }
#endif

 

폰트설정한 텍스트 표시


var guiStyle = new GUIStyle();
guiStyle.alignment = TextAnchor.MiddleCenter; //왜인지 UpperLeft로만 된다
guiStyle.fontSize = 48;
guiStyle.normal.textColor = color;
UnityEditor.Handles.Label(transform.position, "text", guiStyle);

 

 

 

 

선그리기 커스텀

void DrawLine(params Transform[] transforms)
{
    transforms = System.Array.FindAll(transforms, x => x != null);
    if ((transforms == null) || (transforms.Length < 2))
    {
        return;
    }
    for (int i = 0; i < transforms.Length-1; i++)
    {
        Gizmos.DrawLine(transforms[i].position, transforms[i+1].position);
    }
}

 

 

 

회전가능한 Cube

    static void DrawWireCubeOverlay(Vector3 center, Vector3 size, Quaternion rotation)
    {
#if UNITY_EDITOR
        {
            var size1 = size;
            var size2 = size1;
            for (int x = -1; x <= 1; x += 2)
            {
                for (int y = -1; y <= 1; y += 2)
                {
                    size1.x = size.x * x;
                    size1.y = size.y * y;
                    size2 = size1;

                    size1.z = size.z;
                    size2.z = -size1.z;
                    DrawLine(size1, size2);
                }
            }
            for (int y = -1; y <= 1; y += 2)
            {
                for (int z = -1; z <= 1; z += 2)
                {
                    size1.y = size.y * y;
                    size1.z = size.z * z;
                    size2 = size1;

                    size1.x = size.x;
                    size2.x = -size1.x;
                    DrawLine(size1, size2);
                }
            }
            for (int x = -1; x <= 1; x += 2)
            {
                for (int z = -1; z <= 1; z += 2)
                {
                    size1.x = size.x * x;
                    size1.z = size.z * z;
                    size2 = size1;

                    size1.y = size.y;
                    size2.y = -size1.y;
                    DrawLine(size1, size2);
                }
            }
        }
        void DrawLine(Vector3 size1, Vector3 size2)
        {
            UnityEditor.Handles.DrawLine(center + rotation * (size1 / 2), center + rotation*(size2 / 2));
        }
#endif
    }

 

 

 

 

캡슐을 그림

    static void DrawCapsule(float radius, params Transform[] transforms)
    {
        transforms = System.Array.FindAll(transforms, x => x != null);
        if ((transforms == null) || (transforms.Length < 2))
        {
            return;
        }
        for (int i = 1; i < transforms.Length; i++)
        {

            DrawCapsule(transforms[i - 1].position, transforms[i].position, radius);
        }
    }
    static void DrawCapsule(Vector3 start, Vector3 end, float radius)
    {
        var fowordAngle = Quaternion.LookRotation(start - end, Vector3.up);


        start += (end - start).normalized * radius;
        end -= (end - start).normalized * radius;





#if UNITY_EDITOR
        UnityEditor.Handles.DrawWireDisc(start, fowordAngle * Vector3.forward, radius);
        UnityEditor.Handles.DrawWireArc(start, fowordAngle * Vector3.up, fowordAngle * -Vector3.right, 180, radius);
        UnityEditor.Handles.DrawWireArc(start, fowordAngle * Vector3.right, fowordAngle * Vector3.up, 180, radius);

        UnityEditor.Handles.DrawWireDisc(end, fowordAngle * Vector3.forward, radius);
        UnityEditor.Handles.DrawWireArc(end, fowordAngle * Vector3.up, fowordAngle * Vector3.right, 180, radius);
        UnityEditor.Handles.DrawWireArc(end, fowordAngle * Vector3.right, fowordAngle * -Vector3.up, 180, radius);
#endif


        Vector3 upVector = fowordAngle * Vector3.up * radius;
        Vector3 rightVector = fowordAngle * Vector3.right * radius;


#if UNITY_EDITOR
        UnityEditor.Handles.DrawLine(start + upVector, end + upVector);
        UnityEditor.Handles.DrawLine(start + rightVector, end + rightVector);
        UnityEditor.Handles.DrawLine(start - upVector, end - upVector);
        UnityEditor.Handles.DrawLine(start - rightVector, end - rightVector);
#endif

    }

 

 

 

실린더를 그림


    void DrawCylinder(float radius, params Transform[] transforms)
    {
        transforms = System.Array.FindAll(transforms, x => x != null);
        if ((transforms == null) || (transforms.Length < 2))
        {
            return;
        }
        for (int i = 1; i < transforms.Length; i++)
        {

            DrawCylinder(transforms[i - 1].position, transforms[i].position, radius);
        }
    }
    void DrawCylinder(Vector3 start, Vector3 end, float radius)
    {
        var fowordAngle = Quaternion.LookRotation(start - end, Vector3.up);

#if UNITY_EDITOR
        UnityEditor.Handles.DrawWireDisc(start, fowordAngle * Vector3.forward, radius);

        UnityEditor.Handles.DrawWireDisc(end, fowordAngle * Vector3.forward, radius);
#endif


        Vector3 upVector = fowordAngle * Vector3.up * radius;
        Vector3 rightVector = fowordAngle * Vector3.right * radius;


#if UNITY_EDITOR
        UnityEditor.Handles.DrawLine(start + upVector, end + upVector);
        UnityEditor.Handles.DrawLine(start + rightVector, end + rightVector);
        UnityEditor.Handles.DrawLine(start - upVector, end - upVector);
        UnityEditor.Handles.DrawLine(start - rightVector, end - rightVector);
#endif


    }

 

 

 

 

콜라이더를 그림

    void DrawColliderGizmo(Transform transform)
    {
        if (transform != null)
        {
            DrawColliderGizmo(transform.gameObject);
        }
    }
    void DrawColliderGizmo(GameObject gameObject)
    {
        if (gameObject != null)
        {
            var sphereCollider = gameObject.GetComponent<SphereCollider>();
            if (sphereCollider != null)
            {
                Gizmos.DrawWireSphere(transform.position, sphereCollider.radius);
            }

        }
    }

 

 

컬러적용

Gizmos.color = Color.red;
{
    Gizmos.DrawLine(cameraPosition.position, thirdPersonPoint.position);
}
Gizmos.color = Color.white;

 

 

 

선택된 상태에서만 기즈모를 그림

void OnDrawGizmosSelected()
{
    //기즈모를 그림
}

혹은

#if UNITY_EDITOR
        if (Selection.transforms.Contains(transform))
        {
            //기즈모를 그림
        }
#endif

 

 

 

화살표 표시 (arrow)

#if UNITY_EDITOR
Handles.color = Handles.xAxisColor;
UnityEditor.Handles.ArrowHandleCap(0, transform.position, transform.rotation * Quaternion.Euler(0, 90, 0), size: 0.25f, EventType.Repaint);
Handles.color = Handles.yAxisColor;
UnityEditor.Handles.ArrowHandleCap(0, transform.position, transform.rotation * Quaternion.Euler(-90, 0, 0), size: 0.25f, EventType.Repaint);
Handles.color = Handles.zAxisColor;
UnityEditor.Handles.ArrowHandleCap(0, transform.position, transform.rotation, size: 0.25f, EventType.Repaint);
Handles.color = Color.white;
#endif

 

 

 

 

 

EditorWindow에서 그릴때

Debug 계열만 됨

void OnGUI()
{
    if (armTransform != null)
    {
        Debug.DrawLine(armTransform.position, armTransform.position+Vector3.forward,Color.red);
    }
}
void Update()
{
    Repaint();
}

 

'Unity > C#' 카테고리의 다른 글

유니티 커스텀 인터페이스  (0) 2021.06.24
유니티 안드로이드 빌드관련 스크립트  (0) 2021.06.10
유니티 오디오 관련 코드  (0) 2021.06.01
posted by 모카쨩
2021. 6. 12. 01:08

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2021. 6. 10. 18:14 Unity/C#

 

 

 

에셋번들에 포함되는것 : 텍스트파일(단, 리소스 폴더 하위에 있어야함), 스크립트오브젝트

미포함되는것 : 스크립트

'Unity > C#' 카테고리의 다른 글

유니티 기즈모 (Gizmo) 관련코드  (0) 2021.06.15
유니티 오디오 관련 코드  (0) 2021.06.01
오큘러스 함수들  (0) 2021.05.16
posted by 모카쨩
2021. 6. 1. 15:27 Unity/C#
public static void WaveToMP3(string waveFileName, string mp3FileName, NAudio.Lame.LAMEPreset bitRate = NAudio.Lame.LAMEPreset.ABR_128)
{
    using (var reader = new NAudio.Wave.WZT.WaveFileReader(waveFileName))
    using (var writer = new NAudio.Lame.LameMP3FileWriter(mp3FileName, new NAudio.Wave.WZT.WaveFormat(), bitRate))
        reader.CopyTo(writer);
}
public void SaveMp3(string filePath,AudioClip clip)
{
    if (clip == null)
    {
        Debug.LogError("클립없음");
        return;
    }
    var tempPath = Application.temporaryCachePath + "/tempAudio";
    //Debug.Log(tempPath);
    SavWav.Save(tempPath, clip);
    //Debug.Log(filePath);
    WaveToMP3(tempPath, filePath);
    System.IO.File.Delete(tempPath);
}

 

볼륨 프로토 타입

    float GetVolume(float[] audioData, int index, int samplingRate)
    {
        if ((audioData == null) || (audioData.Length == 0))
        {
            return 0;
        }
        float checkTime = 0.05f;

        var startIndex = index;
        var length = Mathf.Min(audioData.Length - index, (int)(samplingRate * checkTime));
        var sliceArray = audioData.Skip(startIndex).Take(length).ToArray();
        //return System.Array.ConvertAll(sliceArray, x => Mathf.Abs(x)).Average();
        if ((sliceArray == null) || (sliceArray.Length == 0))
        {
            return 0;
        }
        return sliceArray.Max();
    }

 

 

 

 

 

 

 

현재 오디오소스의 볼륨을 가져옴

    public AudioSource audioSource;

    float GetVolume(float[] audioData, int index, int samplingRate)
    {
        if ((audioData == null) || (audioData.Length == 0))
        {
            return 0;
        }
        float checkTime = 0.05f;

        var startIndex = index;
        var length = Mathf.Min(audioData.Length - index, (int)(samplingRate * checkTime));
        var sliceArray = audioData.Skip(startIndex).Take(length).ToArray();
        //return System.Array.ConvertAll(sliceArray, x => Mathf.Abs(x)).Average();
        if ((sliceArray == null) || (sliceArray.Length == 0))
        {
            return 0;
        }
        return sliceArray.Max();
    }
    // Update is called once per frame
    void Update()
    {

        var clip = audioSource.clip;
        var ratio = audioSource.time / clip.length;
        var samplingRate = clip.frequency;
        int index = (int)(clip.samples * ratio / clip.channels);
        float[] audioData = new float[clip.samples * clip.channels];
        audioSource.clip.GetData(audioData, 0);
        float volume = GetVolume(audioData, index, samplingRate);
        //float volume2 = audioData[index] - audioData[Mathf.Max(0, index - 1)];


        var localScale = transform.localScale;
        localScale.x= volume;
        transform.localScale = localScale;
    }

 

wav로 저장

https://gist.github.com/darktable/2317063

var savePath = SFB.StandaloneFileBrowser.SaveFilePanel("Save File",directory:"", "defaultName", ".wav"); 
if (savePath == null)
{
    return;
}
SavWav.Save(savePath, clip);

 

 

mp3로 저장 (Unity3D-save-audioClip-to-MP3)

https://github.com/BeatUpir/Unity3D-save-audioClip-to-MP3

var savePath = SFB.StandaloneFileBrowser.SaveFilePanel("Save File",directory:"", "defaultName", ".mp3"); 
if (savePath == null)
{
    return;
}
EncodeMP3.convert(clip, savePath, bitRate: 128);

 

mp3로 저장 (Lame-For-Unity)

위에거보단 느리고 불안정

조심할점은 위의 Unity3D-save-audioClip-to-MP3와 충돌한다는 점이다

https://github.com/3wz/Lame-For-Unity

public static void WaveToMP3(string waveFileName, string mp3FileName, NAudio.Lame.LAMEPreset bitRate = NAudio.Lame.LAMEPreset.ABR_128)
{
    using (var reader = new NAudio.Wave.WZT.WaveFileReader(waveFileName))
    using (var writer = new NAudio.Lame.LameMP3FileWriter(mp3FileName, new NAudio.Wave.WZT.WaveFormat(), bitRate))
        reader.CopyTo(writer);
}
public void SaveMp3(string filePath,AudioClip clip)
{
    if (clip == null)
    {
        Debug.LogError("클립없음");
        return;
    }
    var tempPath = Application.temporaryCachePath + $"/tempAudio.wav";
    //Debug.Log(tempPath);
    SavWav.Save(tempPath, clip);
    //Debug.Log(filePath);
    WaveToMP3(tempPath, filePath);
    System.IO.File.Delete(tempPath);
}

 

 

 

윈도우에서 mp3로드

https://assetstore.unity.com/packages/tools/audio/audioimporter-146746

 

 

 

 

 

 

 

 

 

 

 

 

 

'Unity > C#' 카테고리의 다른 글

유니티 안드로이드 빌드관련 스크립트  (0) 2021.06.10
오큘러스 함수들  (0) 2021.05.16
유니티 에디터 윈도우  (0) 2021.04.12
posted by 모카쨩
2021. 5. 16. 12:51 Unity/C#

 

 

OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, OVRInput.Controller.LTouch);

//얼마나 그랩이 당겨졌는지 반환

'Unity > C#' 카테고리의 다른 글

유니티 오디오 관련 코드  (0) 2021.06.01
유니티 에디터 윈도우  (0) 2021.04.12
코드 모음 사이트  (0) 2021.01.24
posted by 모카쨩

저사양 유저용 블로그 진입