Get it on Google Play


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

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

Recent Comment

Archive


2023. 8. 11. 05:11 Unity



 

 

브챗하면서 썼던 파이널 IK

오랜만에 다시 쓰려고 하니 기억이 안난다

그래서 정리

 

 

 

 

 

 

이건 좀 구형인데 이렇게 하고 타겟을 움직이면 따라간다

 

 

 

 

 

말그대로 Arm IK

Target으로 이동한다

유감스럽게도 아래의 Aim IK랑 동시적용은 안 된다

 

 

 

 

 

Aim IK

총구를 해당 장소에 향하게 할때 쓴다

근데 Aim IK를 쓰면 ParentConstraint가 먹통이 되니 주의

스크립트를 별도로 만들어서 연결시키는거보단 그냥 아마추어 하위에 프리팹 넣어주는게 더 간편할듯

 

Aim Transform은 총구 방향

Ribs는 체스트

Target은 쳐다보는 방향이다

스파인도 있으면 스파인도 넣어주는게 좋다

 

 

 

 

 

 

 

weight 조정

여기 올라간건 구버전이라 코드엔 안 나와있는데

애니메이션이랑 동시에 껐다 켰다 하면

일시적으로 에임 포인트가 차렷기준으로 잡혀서 허리가 돌아가 버린다

반드시 애니메이션을 먼저 키고 그 뒤 IK를 키고

끌때도 IK를 먼거 끄고 애니메이션을 끄자

var aimIK = animator.GetComponent<RootMotion.FinalIK.AimIK>();

var weight = 0f;
var lerpSpeed = 8f*Time.deltaTime;
if (GetWeaponSystem().weaponIndex == 2)
{
}
else
{
    if (attack)
    {
        if (Vector3.Distance(chest.transform.position, crosshair.HitPoint) > 1)
        {
            weight = 1;
        }
    }
    else
    {
        var nowTime = Time.time;
        var delay = 1;
        if (nowTime < weaponSlots[weaponSlotIndex].lastFireTime + delay)
        {
            weight = 1;
        }
        lerpSpeed = 4f * Time.deltaTime;
    }
}
if (GetComponent<PhotonCharacter>().hp <= 0)
{
    weight = 0;
    lerpSpeed = 1;
}
aimIK.solver.IKPositionWeight = Mathf.Lerp(aimIK.solver.IKPositionWeight, weight, lerpSpeed);

 

 

 

'Unity' 카테고리의 다른 글

다이나믹본 설정  (0) 2023.08.12
유니티 NavMesh  (0) 2023.07.16
유니티 애니메이션 관련  (0) 2023.04.03
posted by 모카쨩
2023. 7. 16. 20:00 Unity

 

 

 

길이 가져오기

도달했나 검사할때 씀

remainingDistance가 잘 안작동 해서 만듦

public static float GetPathLength(NavMeshPath path)
{
    float length = 0f;

    if ((path.status != NavMeshPathStatus.PathInvalid) && (path.corners!=null))
    {
        for (int i = 1; i < path.corners.Length; ++i)
        {
            length += Vector3.Distance(path.corners[i - 1], path.corners[i]);
        }
    }
    else
    {
        length = 99999f;
    }

    return length;
}

 

 

 

디버깅용

V1

if (Application.platform==RuntimePlatform.WindowsEditor)
{
    if ((path!=null)
        && (path.status != NavMeshPathStatus.PathInvalid) 
        && (path.corners != null))
    {
        for (int i = 0; i < path.corners.Length - 1; i++)
        {
            Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.green);
        }
    }
}

 

V2

#if UNITY_EDITOR
void OnDrawGizmos()
{
    var agent = GetComponent<NavMeshAgent>();
    if (agent == null)
    {
        UnityEditor.Handles.Label(transform.position, "agent == null");
        return;
    }
    //var path = agent.path;
    if (path == null)
    {
        UnityEditor.Handles.Label(transform.position, "path == null");
        return;
    }
    if (path.status == NavMeshPathStatus.PathInvalid)
    {
        UnityEditor.Handles.Label(transform.position, "path.status == NavMeshPathStatus.PathInvalid");
        return;
    }
    if (path.corners == null)
    {
        UnityEditor.Handles.Label(transform.position, "path.corners == null");
        return;
    }
    if (path.corners.Length < 2)
    {
        UnityEditor.Handles.Label(transform.position, "path.corners.Length < 2");
        return;
    }
    UnityEditor.Handles.Label(transform.position, $"path.corners.Length : {path.corners.Length}\npath.corners[1] : {path.corners[1]}");
    for (int i = 0; i < path.corners.Length - 1; i++)
    {
        Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.green);
    }
    Gizmos.DrawWireSphere(transform.position, agent.stoppingDistance);
}
#endif

 

 

 

 

목적지 설정


public void SetDestination(Transform target)
{
    var agent = GetComponent<NavMeshAgent>();
    if ((target != null) && (agent != null))
    {
        agent.SetDestination(target.position);
    }
    else
    {
        agent.ResetPath();
    }
}

 

 

 

패스를 WASD로 변경



/// <summary>
/// x는 horizon (-1 ~ 1)
/// y는 height (Mathf.NegativeInfinity ~ Mathf.Infinity)
/// z는 vertical (-1 ~ 1)
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
Vector3 Path2WASD(NavMeshPath path)
{
    if (path == null)
    {
        return Vector3.zero;
    }
    if (path.status == NavMeshPathStatus.PathInvalid)
    {
        return Vector3.zero;
    }
    if (path.corners == null)
    {
        return Vector3.zero;
    }
    var agent = GetComponent<NavMeshAgent>();

    var stoppingDistance = 0.1f;
    if (agent!=null)
    {
        stoppingDistance = agent.stoppingDistance;
    }

    if (stoppingDistance > GetPathLength(path))
    {
        return Vector3.zero;
    }



    if (path.corners.Length<2)
    {
        return Vector3.zero;
    }

    var movePos = path.corners[1];


    if (path.corners.Length >= 3)
    {
        if (Vector3.Distance(path.corners[0], path.corners[1]) < 0.1f)
        {
            movePos = path.corners[2];
        }
    }
    Debug.DrawLine(transform.position + Vector3.up * 0.1f, movePos + Vector3.up * 0.1f, Color.blue);

    var relativePosition = Quaternion.Inverse(transform.rotation) * (movePos - transform.position);
    var relativePosition2D = new Vector2(relativePosition.x, relativePosition.z).normalized;
    relativePosition = new Vector3(relativePosition2D.x, relativePosition.y, relativePosition2D.y);

    Debug.DrawLine(transform.position + Vector3.up * 0.2f, transform.position + transform.rotation*relativePosition + Vector3.up * 0.2f, Color.red);
    return relativePosition;
}

 

'Unity' 카테고리의 다른 글

유니티 Final IK  (0) 2023.08.11
유니티 애니메이션 관련  (0) 2023.04.03
구글플레이 앱 이전  (0) 2023.03.06
posted by 모카쨩
2023. 4. 25. 03:07 Unity/shader

 

Shader "Perlin/Noise"
{
    Properties
    {
        [HideInInspector]_MainTex ("Texture", 2D) = "white" {}
		[PowerSlider(4)]_Scale("Scale", Range(0,8192)) = 1000
		_Speed("Speed", Range(0,8)) = 0
		//[HideInInspector]
        _Key("Key", float) = 0
    }
    SubShader
    {
		Tags{
			"RenderType" = "Transparent"
			"Queue" = "Transparent"
            "IgnoreProjector"="True"
		}

        LOD 100
        
		blend srcalpha oneminussrcalpha
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"
            float _Speed;
            float _Key;
            float interpolate(float a0, float a1, float w) {
                /* // You may want clamping by inserting:
                 * if (0.0 > w) return a0;
                 * if (1.0 < w) return a1;
                 */
                return (a1 - a0) * w + a0;
                /* // Use this cubic interpolation [[Smoothstep]] instead, for a smooth appearance:
                 * return (a1 - a0) * (3.0 - w * 2.0) * w * w + a0;
                 *
                 * // Use [[Smootherstep]] for an even smoother result with a second derivative equal to zero on boundaries:
                 * return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0;
                 */
            }
            float2 randomGradient(int ix, int iy) {
                // No precomputed gradients mean this works for any number of grid coordinates
                uint w = 8 * (4294967295+1);
                uint s = w / 2; // rotation width
                uint a = ix, b = iy;
                a *= 3284157443; 
                b ^= a << s | a >> w-s;
                b *= 1911520717; 
                a ^= b << s | b >> w-s;
                a *= 2048419325;
                float random = a * (3.14159265 / ~(~0u >> 1)); // in [0, 2*Pi]
                random += _Time.y*_Speed;
                random += _Key;
                float2 v;
                v.x = cos(random); v.y = sin(random);
                return v;
            }
            // Computes the dot product of the distance and gradient vectors.
            float dotGridGradient(int ix, int iy, float x, float y) {
                // Get gradient from integer coordinates
                float2 gradient = randomGradient(ix, iy);

                // Compute the distance vector
                float dx = x - (float)ix;
                float dy = y - (float)iy;

                // Compute the dot-product
                return (dx*gradient.x + dy*gradient.y);
            }
            // Compute Perlin noise at coordinates x, y
            float perlin(float x, float y) {
                // Determine grid cell coordinates
                int x0 = (int)floor(x);
                int x1 = x0 + 1;
                int y0 = (int)floor(y);
                int y1 = y0 + 1;

                // Determine interpolation weights
                // Could also use higher order polynomial/s-curve here
                float sx = x - (float)x0;
                float sy = y - (float)y0;

                // Interpolate between grid point gradients
                float n0, n1, ix0, ix1, value;

                n0 = dotGridGradient(x0, y0, x, y);
                n1 = dotGridGradient(x1, y0, x, y);
                ix0 = interpolate(n0, n1, sx);

                n0 = dotGridGradient(x0, y1, x, y);
                n1 = dotGridGradient(x1, y1, x, y);
                ix1 = interpolate(n0, n1, sx);

                value = interpolate(ix0, ix1, sy);
                return value; // Will return in range -1 to 1. To make it in range 0 to 1, multiply by 0.5 and add 0.5
            }
            float perlin(float2 uv) {
                return perlin(uv.x,uv.y)*0.5+0.5; 
            }
            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _Scale;
            
            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }


            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = 1;
                col.rgb = perlin(i.uv*_Scale);
                return col;
            }
            ENDCG
        }
    }
}

 

내가 포팅한 펄린노이즈임

원문은 https://en.wikipedia.org/wiki/Perlin_noise 에서 가져왔고

포팅만 했을뿐 만든건 Ken Perlin이므로 어떻게 쓰던 알바아님😜

자기가 포팅했다고 하는 노양심짓만 안 해주면 좋을듯

'Unity > shader' 카테고리의 다른 글

DepthCameraTexture를 _CameraDepthTexture처럼 쓰기  (0) 2023.10.14
스크린 오버레이 샘플  (0) 2023.01.20
유니티 스카이박스 관련  (0) 2023.01.16
posted by 모카쨩
2023. 4. 3. 11:04 Unity

 

 

 

임포트시 설정별 차이

'Unity' 카테고리의 다른 글

유니티 NavMesh  (0) 2023.07.16
구글플레이 앱 이전  (0) 2023.03.06
유니티 파티클, 트레일, 라인 렌더러  (0) 2023.01.21
posted by 모카쨩
2023. 3. 6. 16:22 Unity

계정 ID와 트랜잭션 ID 찾는법은 하단 참조

 

 

 

 

 

 

계정 ID 찾는법

 

 

 

 

 

 

 

트랜잭션 아이디는 지메일에서 개발자 등록 당시 냈던 요금의 영수증에서 찾을수 있다

 

신버전

 

구버전

 

 

 

 

 

휴 제일 큰 고생이 끝났다

 

이전할 앱을 추가하자

 

 

 

 

 

 

 

 

 

 

 

 

그러면 수신측에서 이런 메일이 온다

요청검토를 눌러주고

 

마찬가지로 동의 및 이전을 눌러주자

 

 

 

 

 

 

다만 계정이 바뀌어서 그런지 광고 SDK에 문제가 좀 생긴다나 보다

아직 확인은 안 해봄

'Unity' 카테고리의 다른 글

유니티 애니메이션 관련  (0) 2023.04.03
유니티 파티클, 트레일, 라인 렌더러  (0) 2023.01.21
유니티 창위치 설정  (0) 2022.06.18
posted by 모카쨩
2023. 1. 21. 23:55 Unity

 

파티클의 startLifeTime

//읽을때
var startLifetime=particleEffect.main.startLifetime.constant;


//쓸때
var particleEffectMain = particleEffect.main;
var startLifetime = particleEffectMain.startLifetime;
startLifetime.constant = 설정할시간;
particleEffectMain.startLifetime = startLifetime;

 

파티클 텍스처 변경

var renderer = particle.GetComponent<Renderer>();
renderer.material.mainTexture = sprite.texture;

 

파티클 데이터 수정

//생성
{
    var particleSystem = GetComponent<ParticleSystem>();
    var particles = new ParticleSystem.Particle[100];
    for (int i = 0; i < particles.Length; i++)
    {
        particles[i] = new ParticleSystem.Particle();
        particles[i].position = new Vector3(0, i * 0.1f, 0);
        particles[i].startSize = particleSystem.main.startSize.Evaluate(0);
        particles[i].rotation3D = new Vector3(0, i * 10, 0);
    }
    particleSystem.SetParticles(particles);
}

//읽기
{
    var particleSystem = GetComponent<ParticleSystem>();
    var particles = new ParticleSystem.Particle[particleSystem.particleCount];
    particleSystem.GetParticles(particles);
    for (int i = 0; i < particles.Length; i++)
    {
        Debug.Log($"particles[{i}].position: {particles[i].position}");
        Debug.Log($"particles[{i}].rotation3D: {particles[i].rotation3D}");
        
        Debug.DrawLine(particles[i].position, particles[i].position+Quaternion.Euler(particles[i].rotation3D) * Vector3.forward*0.1f);
        Debug.DrawLine(particles[i].position, particles[i].position + Quaternion.Euler(particles[i].rotation3D) * Vector3.up * 0.1f);
        //Debug.Log($"Quaternion.Euler(particles[{i}].rotation3D): {Quaternion.Euler(particles[i].rotation3D)}");
    }
}

//수정
{
    var particleSystem = GetComponent<ParticleSystem>();
    var particles = new ParticleSystem.Particle[particleSystem.particleCount];
    particleSystem.GetParticles(particles);
    for (int i = 0; i < particles.Length; i++)
    {
        particles[i].position = new Vector3(0, i * 0.1f, 0);
    }
    particleSystem.SetParticles(particles);
}

 

 

 

라인렌더러 좌표를 트랜스폼들 좌표로 설정

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


#if UNITY_EDITOR

using UnityEditor;
[CustomEditor(typeof(TransformsLine))]
public class TransformsLineEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();//기본 인스펙터를 받아올때
        serializedObject.Update();
        {
            if (GUILayout.Button("Preview"))
            {
                ((FishingLine)target).SetLineRenderer();
            }
        }
        serializedObject.ApplyModifiedProperties();


    }
}

#endif

public class TransformsLine : MonoBehaviour
{

    public Transform[] transforms;
    public LineRenderer lineRenderer;
    // Start is called before the first frame update
    void Start()
    {
        lineRenderer = lineRenderer ?? GetComponent<LineRenderer>();
    }

    // Update is called once per frame
    public void SetLineRenderer()
    {
        if ((lineRenderer != null) && (transforms.Length > 0))
        {
            lineRenderer.SetPositions(System.Array.ConvertAll(transforms, transform => transform.position));
        }
    }
    // Update is called once per frame
    void Update()
    {
        SetLineRenderer();
    }
}

 

 

 

 

 

 

트레일 Positions 구조

//1번라인
(0: (-0.3, 0.7, 0.0))(1: (-0.3, 0.7, 0.0))(2: (-0.4, 0.8, 0.1))
(3: (-0.6, 1.0, 0.4))(4: (-0.5, 1.1, 0.5))(5: (-0.5, 1.2, 0.5))
(6: (-0.5, 1.3, 0.5))(7: (-0.5, 1.3, 0.5))(8: (-0.5, 1.2, 0.6))
(9: (-0.5, 1.0, 0.6))(10: (-0.5, 0.9, 0.6))(11: (-0.5, 0.8, 0.6))

//2번라인
(12: (-0.5, 0.9, 0.7))(13: (-0.5, 0.9, 0.7))(14: (-0.4, 1.0, 0.8))
(15: (-0.4, 1.0, 0.8))(16: (-0.4, 1.0, 0.8))(17: (-0.4, 1.0, 0.8))
(18: (-0.4, 1.1, 0.8))(19: (-0.4, 1.1, 0.8))(20: (-0.4, 1.1, 0.8))
(21: (-0.4, 1.0, 0.9))(22: (-0.4, 1.0, 0.9))(23: (-0.4, 0.9, 0.9))

동일한 좌표를 두번 찍는것으로 시작점을 표현

 

'Unity' 카테고리의 다른 글

구글플레이 앱 이전  (0) 2023.03.06
유니티 창위치 설정  (0) 2022.06.18
유니티 csv 에셋  (0) 2022.04.30
posted by 모카쨩
2023. 1. 20. 07:49 Unity/shader

 

1:1

 

2:1 크롭

 

 

Shader "Ahzkwid/ScreenOverlay"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            

            v2f vert (appdata v)
            {
                v2f o;
				o.uv = float4(TRANSFORM_TEX(v.uv, _MainTex),1,1);
				o.vertex.xy = o.uv;
				o.vertex.xy -= 0.5;
				o.vertex.xy *= 2;
				o.vertex.y = -o.vertex.y;
				o.vertex.zw = 1;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed2 uv=i.uv;
                
				float screenWid = _ScreenParams.x / _ScreenParams.y;
				float texelWid = _MainTex_TexelSize.z / _MainTex_TexelSize.w;
                if(screenWid>texelWid)
                {
                    uv.x*=screenWid;
			        uv.x -= screenWid / 2;
			        uv.x += texelWid / 2;
                    uv.x/=texelWid;
                }
                else
                {

				    float screenHei = 1/screenWid;
				    float texelHei = 1/texelWid;

                    uv.y*=screenHei;
			        uv.y -= screenHei / 2;
			        uv.y += texelHei / 2;
                    uv.y/=texelHei;
                }

                fixed4 col = tex2D(_MainTex, uv);
                col.a*=all(uv==saturate(uv));
                return lerp(0,col,col.a);
            }
            ENDCG
        }
    }
}

'Unity > shader' 카테고리의 다른 글

PerlinNoise HLSL  (0) 2023.04.25
유니티 스카이박스 관련  (0) 2023.01.16
함수 그래프 모음  (0) 2022.01.15
posted by 모카쨩
2023. 1. 16. 21:41 Unity/shader
Shader "Skybox/Sample"
{
    Properties
    {
        [NoScaleOffset] _Tex ("Cubemap   (HDR)", Cube) = "grey" {}
    }
    SubShader
    {
        Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float3 texcoord : TEXCOORD0;
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            samplerCUBE _Tex;
            half4 _Tex_HDR;

            v2f vert (appdata v)
            {
                v2f o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.vertex.xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                half4 tex = texCUBE (_Tex, i.texcoord);
                fixed3 col = DecodeHDR (tex, _Tex_HDR);
                return half4(col, 1);
            }
            ENDCG
        }
    }
}

샘플코드

 

 

 

'Unity > shader' 카테고리의 다른 글

스크린 오버레이 샘플  (0) 2023.01.20
함수 그래프 모음  (0) 2022.01.15
Decal Shader  (0) 2022.01.13
posted by 모카쨩

  • total
  • today
  • yesterday

Recent Post

저사양 유저용 블로그 진입