반응형
Notice
Recent Posts
Recent Comments
«   2024/04   »
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
Archives
Today
Total
관리 메뉴

Do Something IT

[Unity3d] 케릭터 이동과 카메라도 같이 이동 및 회전 본문

Unity3D

[Unity3d] 케릭터 이동과 카메라도 같이 이동 및 회전

아낙시만더 2013. 5. 10. 11:31
반응형

출처: 바로가기 

케릭터 이동


Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0

Input.GetAxis("Vertical"));



moveDirection = transform.TransformDirection(moveDirection);

moveDirection *= Time.fixedDeltaTime;

moveDirection *= mSpeed;


moveDirection += transform.position;

transform.position = moveDirection;


방향키로 입력된 곳으로 일정한 크기로 이동하게 한다.




케릭터가 이동할 때 카메라도 같이 이동하게 하려면


가장 간단한 방법!


케릭터 자식으로 카메라는 넣는다. !



그 후 카메라는 케릭터의 이동과 방향에 맞게 설정해주면 된다.


Transform mCamera;


mCamera = transform.FindChild("Camera");

mCamera.transform.LookAt( transform.position );

mCamera.transform.RotateAround( transform.position, Vector3.up, transform.rotation.z );



자식들중에 Camera를 찾고, 케릭터의 위치를 바라보게 한다.
처음 카메라 위치는 툴상에서 케릭터의 뒤,위에 넣어놨다. 
일반적인 mmorpg 게임 뷰 처럼..

그러면 카메라는 케릭터가 바라보는 곳을 무조건 바라보게 되니,
케릭터를 회전 시키면 카메라는 저절로 정면을 응시하게 된다.




케릭터 회전

Vector3 prePosition = moveDirection;


Quaternion toRotation = transform.rotation * Quaternion.LookRotation( prePosition ) ;

transform.rotation = Quaternion.Slerp( transform.rotation, 

toRotation, Time.fixedDeltaTime );



현재 회전벡터(transform.rotaion)와 이동할 방향 (prePosition)의 회전 벡터를 곱함으로써

현재의 회전에서 이동해야할 회전방향을 구할 수 있다.


toRotation을 바로 회전벡터로 지정하면 케릭터는 회전이 된다.

하지만 너무 빠르다! 미치도록..뱅글뱅글 돌아버린다.


그렇기 때문에 현재 회전과 이동할 회전의 사이값으로 조금씩만 돌기 위하여 구 보간(Quaternion.Slerp)을 한다.


반응형
Comments