본문 바로가기

# 프로그래밍 개발/01. Unity

유니티 캐릭터 원하는 각도만큼 회전하기 Rotation with IEnumerator Coroutine

반응형

#1 Unity Character Rotation with IEnumerator Coroutine

간혹 Update() 내에서 캐릭터를 회전하는 경우가 아니라, Coroutine을 활용해서 비동기적으로 캐릭터를 회전시키는 경우가 있습니다. 

다음의 코드를 활용하여 현재 캐릭터의 각도에서부터 원하는 만큼 회전을 시킬 수 있습니다. 

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
private Transform tr;
private Start(){
    tr = gameObject.transform;
}
 
private void Rotation(){
    float TargetAngle = 90f;
    StartCoroutine(iRotation(TargetAngle))
}
 
IEnumerator iRotation(float targetAngle){
    float st = tr.eulerAngles.y;
    float er = targetAngle;
 
    float t = 0f;
    
    while (t < 1.5f)
    {
        t += Time.deltaTime;
        float speed = t;
        float yRotation = Mathf.Lerp(st, er, speed) % 360.0f;
 
        tr.eulerAngles = new Vector3(tr.eulerAngles.x, yRotation, tr.eulerAngles.z);
        // Debug.Log(yRotation + " " + transform.eulerAngles.y);
        
        yield return null;
    }
}
cs

 

 

※ 본 포스팅은 기록을 목적으로 하고 있습니다. 제가 사용했던 코드이지만 적용되지 않을 수도 있습니다. 

 

 

 

 

 

 

반응형