Get it on Google Play


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

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

Recent Comment

Archive


'Unity'에 해당되는 글 178건

  1. 2023.09.09 Path 연산
  2. 2023.09.08 유니티 APK 용량
  3. 2023.08.28 유니티 킬로그
  4. 2023.08.23 유니티 플랫폼 훅
  5. 2023.08.19 유니티 웨이포인트식 자율주행
  6. 2023.08.13 ugui에 3d 넣기
  7. 2023.08.12 다이나믹본 설정
  8. 2023.08.12 포톤 기초
2023. 9. 9. 19:09 Unity/C#

 

 

 

생각보다 쓸일이 많더라

한 점에서 Path까지의 최단지점

맨 위에건 AI가 짜주었다

    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);
        return a + ab * t;
    }
    Vector3 ClosestPoint(Vector3 position, List<Vector3> path)
    {
        var closestIndex = ClosestIndex(position, path);
        var point = ClosestPoint(path[closestIndex], path[closestIndex + 1], position);

        return point;
    }
    int ClosestIndex(Vector3 position, List<Vector3> path)
    {
        float minDistance = float.MaxValue;
        int closestIndex = 0;

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

            if (distance < minDistance)
            {
                minDistance = distance;
                closestIndex = i;
            }
        }

        return closestIndex;
    }
    float ClosestLenth(Vector3 position, List<Vector3> path)
    {
        var closestIndex = ClosestIndex(position, path);
        var closestLenth = 0f;

        for (int i = 0; i < closestIndex; i++)
        {
            closestLenth += Vector3.Distance(path[i], path[i + 1]);
        }
        if (path.Count > 1)
        {
            var closestPoint = ClosestPoint(path[closestIndex], path[closestIndex + 1], position);
            closestLenth += Vector3.Distance(path[closestIndex], closestPoint);
        }

        return closestLenth;
    }

 

 

 

총 길이

    float TotalLength(List<Vector3> path)
    {
        float totalLength = 0;
        for (int i = 0; i < path.Count - 1; i++)
        {
            totalLength += Vector3.Distance(path[i], path[i + 1]);
        }
        return totalLength;
    }

 

 

Progress 변환

위에 두개가 있어야 쓸수 있다

나중에 생각해봤는데 ProgressToPosition보다 lerp라고 쓰는게 나을듯


    float GetProgress(Vector3 a, Vector3 b, Vector3 position)
    {
        var ab = b - a;
        var ap = position - a;
        var progress = Vector3.Dot(ap, ab) / Vector3.Dot(ab, ab);
        return Mathf.Clamp01(progress);
    }
    float GetProgress(Vector3 position, List<Vector3> path)
    {
        var progress = ClosestLenth(position, path) / TotalLength(path);
        return Mathf.Clamp01(progress);
    }
    Vector3 ProgressToPosition(Vector3 a, Vector3 b,float progress)
    {
        return a+ (b - a) * Mathf.Clamp01(progress);
        //rotation = Quaternion.LookRotation(ab); //이정돈 외부에서 처리하라고
    }
    (Vector3 position, Quaternion rotation) ProgressToPosition(float progress,List<Vector3> path)
    {
        progress = Mathf.Clamp01(progress);
        float totalLength = TotalLength(path);
        float currentLength = progress * totalLength;
        float accumulatedLength = 0;

        for (int i = 0; i < path.Count - 1; i++)
        {
            float segmentLength = Vector3.Distance(path[i], path[i + 1]);
            if (accumulatedLength + segmentLength > currentLength)
            {
                float t = (currentLength - accumulatedLength) / segmentLength;
                var position = Vector3.Lerp(path[i], path[i + 1], t);
                var rotation = transform.rotation;
                if (path.Count >= 2)
                {
                    rotation = Quaternion.LookRotation(path[i + 1] - path[i]);
                }
                return (position, rotation);
            }
            accumulatedLength += segmentLength;
        }
        {
            var position = path[path.Count - 1];
            var rotation = transform.rotation;
            if (path.Count >= 2)
            {
                rotation = Quaternion.LookRotation(path[path.Count - 1] - path[path.Count - 2]);
            }
            return (position, rotation);
        }
    }

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

자주 쓰는 DateTime 코드 모음  (0) 2023.12.19
csv 사용법  (0) 2022.03.06
Windows DLL경로  (0) 2022.02.12
posted by 모카쨩
2023. 9. 8. 14:55 Unity

 

빌드 했는데 용량이 45MB나 나옴 (뭐?)

그래서 뭐가 원인인지 알아보기로 했다

 

 

누르고

Build Report를 검색해서 제일 밑에거를 본다

빌드할때마다 아래에 생기는듯

 

 

암튼 해서 보면 텍스처가 제일 큰 원인인데

뭔 쓰지도 않는 좀버니니 뭐니 하는게 돌아다닌다

찾아가서 줘패주고 빌드 하니 용량이 35MB까지 줄었다

더 찾아내서 줘패면 20MB까지 가능할듯

 

'Unity' 카테고리의 다른 글

유니티 캐릭터 추적 마커  (0) 2023.09.21
유니티 킬로그  (0) 2023.08.28
유니티 플랫폼 훅  (0) 2023.08.23
posted by 모카쨩
2023. 8. 28. 04:34 Unity

 

 

KillPeed 라고도 한다

어려운건 아닌데 ㅈㄴ 귀찮다

계층구조는 이렇고

컴포넌트는 하단처럼 심어주자

 

사용된 코드는 이 두개

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

public class KillPeed : MonoBehaviour
{
    public KillPeedSlot killPeedSlotPrefab;
    List<KillPeedSlot> killPeedSlots= new List<KillPeedSlot>();
    public float displayTime = 5; //5초후삭제
    public Color enemyColor=Color.red;
    public Color allyColor = Color.blue;
    // Start is called before the first frame update
    void Start()
    {
        killPeedSlotPrefab.gameObject.SetActive(false);
    }
    public void Add(string source, string target,Sprite icon, Color sourceColor, Color targetColor, bool critical = false, bool highlight=false)
    {
        killPeedSlots = killPeedSlots.FindAll(x => x != null);//시간경과로 지워진건 제외
        if (killPeedSlots.Count>=3)//3칸 넘으면 오래된거 삭제
        {
            Destroy(killPeedSlots[0].gameObject);
        }

        var instant = Instantiate(killPeedSlotPrefab, killPeedSlotPrefab.transform.parent);
        instant.source.color = sourceColor;
        instant.target.color = targetColor;
        instant.source.text = source;
        instant.target.text = target;
        instant.icon.sprite = icon;
        instant.critical.SetActive(critical);
        instant.gameObject.SetActive(true);
        if (highlight)
        {
            instant.Highlight();
        }
        Destroy(instant.gameObject, displayTime); 
        killPeedSlots.Add(instant);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class KillPeedSlot : MonoBehaviour
{
    public Text source;
    public GameObject critical;
    public Image icon;
    public Text target;
    void Update()
    {
        GetComponent<ContentSizeFitter>().enabled = false;
        GetComponent<ContentSizeFitter>().enabled = true;
    }
    public void Highlight()
    {
        var color = GetComponent<Image>().color;
        color.r = 1f- color.r;
        color.g = 1f - color.g;
        color.b = 1f - color.b;
        GetComponent<Image>().color = color;
        icon.color = Color.black;
    }
}

 

'Unity' 카테고리의 다른 글

유니티 APK 용량  (0) 2023.09.08
유니티 플랫폼 훅  (0) 2023.08.23
유니티 웨이포인트식 자율주행  (0) 2023.08.19
posted by 모카쨩
2023. 8. 23. 10:46 Unity

 

 

 

검색해보면 여러가지 나온다

바닥오브젝트에 Parent 시키라느니

바닥오브젝트에 포지션값을 계산해서 추적시키라느니

심지어 AI도 이런 개소리를 한다

 

결론부터 말하자면

다 개소리고 그냥 유니티 물리엔진이 기본으로 지원해준다

 

 

근데 잘 보면 스피어는 각도추적이 안 되고 덩그러니 있는걸 볼수 있다

캡슐도 같은 문제다

아마 충돌면이 점이라서 마찰력 0으로 가정하나본데

당연히도 캐릭터들도 캡슐콜라이더를 많이 쓰기 때문에 같은 현상이 생긴다

(대체 언놈이 캡슐콜라이더 쓰라고 선동하고 다닌거지)

 

아무튼 그래서 해결방법

 

발이 닿는 부분에 박스콜라이더를 깔아준다

박스콜라이더가 위아래로 길쭉한 이유는 납작하게 하니 땅에 박힐때도 있드라

아이스크림 콘모양이 되어야 한다

 

 

 

Y축만 풀어주자

 

 

 

플랫폼 설정 차례다

그리고 가끔 패스이동등을 위해 좌표이동을 쓰는것들이 있는데

하단과 같이 치환해주면 된다

 

 

1안

velocity 이동

외력이 가해지면 날아가버리는 단점이 있다

더보기
private void FixedUpdate()
{
    //if (Time.time>1)
    {
        (var pos, var rot) = ProgressToPayloadPosition(progress);

        //rot= Quaternion.Lerp(payload.transform.rotation, rot, 0.1f);
        if (Vector3.Distance(payload.transform.position, pos)>2f)//2이상 이동은 텔레포트로 간주
        {
            payload.transform.position = pos;
            payload.transform.rotation = rot;
        }
        else
        {
            rot= Quaternion.Lerp(payload.transform.rotation, rot, 0.05f); //러프 반영

            var velocity = pos - payload.transform.position;
            //velocity는 초당 이동이므로 프레임당 이동으로 바꾸어주어야 한다고 하는데 어째선지 fixedDeltaTime을 넣으면 급가속으로 위치가 튄다
            //그래서 drag를 넣을까 했는데 얼마만큼 영향준다고도 안 써있고해서 그냥 퍼센테이지로 깎기로 함
            velocity /= Time.fixedDeltaTime;
            velocity *= 0.2f;
            payload.GetComponent<Rigidbody>().velocity = velocity;

            var angularVelocity = (rot * Quaternion.Inverse(payload.transform.rotation)).eulerAngles;
            angularVelocity.x = Mathf.DeltaAngle(0, angularVelocity.x);
            angularVelocity.y = Mathf.DeltaAngle(0, angularVelocity.y);
            angularVelocity.z = Mathf.DeltaAngle(0, angularVelocity.z);
            //얜 그냥 난리 부르스 추길래 fixedDeltaTime 안 넣음, 알고보니 맥스가 7이고 어째 얜 프레임당 기준인듯?
            payload.GetComponent<Rigidbody>().angularVelocity = angularVelocity;
        }


    }
}

 

그리고 가급적 플랫폼 질량을 높여두고

angular drag때문에 원하는 위치에 미반영 되는걸 막기위해 가급적 0으로 두자

 

 

 

2안

애니메이션 피직스를 사용

첫번째는 물리적인 이동이지만

이건 애니메이션이라 예정 좌표 말고 다른곳으로 가지 않는다

 

 

 

3안

이녀석에 페이로드에 제일 적합했다

애니메이션으로 균일한 이동속도는 만들기 어려우니까

(var pos, var rot) = ProgressToPayloadPosition(progress);

if (Vector3.Distance(payload.transform.position, pos) > 2f)//2이상 이동은 텔레포트로 간주
{
    payload.transform.position = pos;
    payload.transform.rotation = rot;
}
else
{
    pos = Vector3.Lerp(payload.transform.position, pos, 0.05f); //덜컹거림 방지
    rot = Quaternion.Lerp(payload.transform.rotation, rot, 0.05f); //덜컹거림 방지
    payload.GetComponent<Rigidbody>().MovePosition(pos);
    payload.GetComponent<Rigidbody>().MoveRotation(rot);
}

 

 

적용된 모습

 

 

 

 

'Unity' 카테고리의 다른 글

유니티 킬로그  (0) 2023.08.28
유니티 웨이포인트식 자율주행  (0) 2023.08.19
ugui에 3d 넣기  (0) 2023.08.13
posted by 모카쨩
2023. 8. 19. 09:18 Unity

 

개 노가다인데 게임오브젝트를 이렇게 촘촘히 박고

잘 기억은 안 나는데

해당 오브젝트 인근으로 이동하면 저기 있는 Target을 다음 지점으로 텔레포트 시켰던거 같다

기본상태에서는 Target을 차량의 살짝 앞에 뒀던거 같음

오랜만에 열어봤는데 일부 컴포넌트 유실이라...

'Unity' 카테고리의 다른 글

유니티 플랫폼 훅  (0) 2023.08.23
ugui에 3d 넣기  (0) 2023.08.13
다이나믹본 설정  (0) 2023.08.12
posted by 모카쨩
2023. 8. 13. 23:05 Unity

 

 

 

 

 

 

RawImage의 사이즈는

Render Camera Size / Canvas Scale * 2

하면 된다

 

 

 

 

 

 

결과물

 

화면비율 바꿔도 잘 된다

 

 

근데 이거 진짜 치명적인 문제가 있는데

캔버스의 렌더카메라에 할당되면 최우선으로 처리되기 때문에

같은 씬 안에 있는 모든 캔버스들이 최상단으로 올라온다. 어흑 마이깟

같은씬안에 캔버스를 다 꺼버려야 써먹을수 있다

 

 

 

 

 

 

다른 방법

 

더보기

 

카메라 할당을 전제로 해서 쓰면 평범하게 잘 된다

복잡한 게임은 멀티 카메라가 기본이니 힘들겠지만
단순한 게임은 이걸로 가능

 

 

다른 방법 2

대신 이건 LateUpdate에 뭔가 다른 카메라 로직 있으면 딜레이가 생긴다

public Transform camaraTracking;
void CameraTracking()
{
    var cam = Camera.main;
    if (cam)
    {
        camaraTracking.position = cam.transform.position;
        camaraTracking.rotation = cam.transform.rotation;
    }
}
void LateUpdate()
{
    CameraTracking();
}

 

 

 

'Unity' 카테고리의 다른 글

유니티 웨이포인트식 자율주행  (0) 2023.08.19
다이나믹본 설정  (0) 2023.08.12
유니티 Final IK  (0) 2023.08.11
posted by 모카쨩
2023. 8. 12. 21:18 Unity

루트본 설정할때 흰색선으로 나타나는 본을 확인하면서 맞추자


damping 탄성값, 젤리같은거 설정할때 낮출수록 좋음, 높을수록 스프링처럼 튀는거를 방지
elasticity 탄력값, 변형으로부터 얼마나 빨리 돌아올지
stffness 단단함, 관성에 얼마나 영향을 받을지,0으로 하면 움직여도 제자리
inert 둔한, 얼마나 늦게 반응할지 인듯? 아니면 다이나믹을 얼마나 적용할지일듯

 

 

 

 

옷, 헤어 등

 

 

가슴

 

 

꼬리

'Unity' 카테고리의 다른 글

ugui에 3d 넣기  (0) 2023.08.13
유니티 Final IK  (0) 2023.08.11
유니티 NavMesh  (0) 2023.07.16
posted by 모카쨩
2023. 8. 12. 18:50 Unity/Photon

 

 

 

또 오랫동안 안 쓰니 자꾸 까먹는다

기초를 까먹어서 나중에 찾는데 안 보임 ㅋㅋ;;

 

 

 

Photon Transform View

포톤판 ObjectSync이다

상위에 Photon View 있어야 함

 

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

자주 쓰는 유니티 포톤챗 코드  (0) 2021.12.14
포톤 오류,에러 모음  (0) 2021.12.08
포톤 친구랑 같이 플레이  (0) 2021.11.24
posted by 모카쨩

  • total
  • today
  • yesterday

Recent Post

저사양 유저용 블로그 진입