[Unity] Transform의 속성과 메서드/플레이어 이동, 회전, 크기 조절
https://www.youtube.com/watch?v=vfR1vOVNW7U
위의 영상을 바탕으로 작성하였습니다.
이동
1.
void update{
if(Input.GetKey(KeyCode.W)){ // w키를 누르면
this.transform.position = this.transform.position + new Vector3(0,0,1) * Time.deltaTime;
// 1초에 z축의 방향으로 1씩 이동한다
}
}
Time.deltaTime을 쓰는 이유 : 위의 코드에서 만약 deltaTime을 안 쓴다면 1프레임에 1씩 오브젝트가 z축으로 이동할 것이다. 그러면 59프레임인 컴퓨터에서는 1초에 59 이동하고 61프레임인 컴퓨터에서는 1초에 61을 이동하므로 시간에 따른 이동 거리를 통일시키기 위해서는 1초에 1씩 움직일 수 있게 deltaTime을 써야한다.
2.
void update{
if(Input.GetKey(KeyCode.W)){ // w키를 누르면
this.transform.Translate(new Vector3(0,0,1) * Time.deltaTime);
// 1초에 z축의 방향으로 1씩 이동한다
}
}
회전
1.
void update{
if(Input.GetKey(KeyCode.W)){ // w키를 누르면
this.transform.eulerAngles = transform.eulerAngles + new Vector3(90,0,0) * Time.deltaTime;
// 1초에 x축을 기준으로 90도 회전
// 오일러 앵글(eulerAngles) = 유니티의 rotation 생각하면 됨
}
}
이런식으로 하면 rotation에서 x가 90이 일때 오브젝트가 부들부들하기만 하고 90도를 넘어가지 못한다. 겉으로 보여지는 값과 내부적으로 계산되는 값이 다르기 때문이다.(transform.eularAngles는 값이 바뀌는데 그 바뀐 값을 받아오고 그 값에 Vector3(90,0,0)을 더해주니까 그런 것임.) 그래서 값을 고정시켜야 한다.
Vector3 rotation;
void Start(){
rotation = this.transform.eulerAngles; // 초기값으로 고정값
}
void update{
if(Input.GetKey(KeyCode.W)){ // w키를 누르면
rotation = rotation + new Vector3(90,0,0) * Time.deltaTime;
this.transform.eulerAngles = rotation;
// 1초에 x축을 기준으로 90도 회전
Debug.Log(transform.eulerAngles);
}
}
이렇게 해야 rotation값에서 계속 증가 된다. 근데 이렇게 해보면 inspector의 rotation값과 debug에 찍히는 오일러 값이 다를 것이다. 왜냐하면 유니티는 자체적으로 쿼터니언을 써서 회전을 시키기 때문에 오일러 앵글이 내부적으로 쿼터니언으로 바뀐다. 그래서 inspecter창의 rotation에서의 오일러 값과 debug에 찍히는 오일러 값이 다른 것이다.
2.
if(Input.GetKey(KeyCode.W)){
this.transform.Rotate(new Vector3(90,0,0) * Time.deltaTime);
}
3.
Vector3 rotation;
void Start(){
rotation = this.transform.eularAngles;
}
if(Input.GetKey(KeyCode.W)){
rotation = rotation + new Vector3(90,0,0) * Time.deltaTime
this.transform.rotation = new Quaternion.Euler(rotation);
}
쿼터니언에 직접 값을 대입하는 건 위험하므로 Euler를 이용해 쓴다.
쿼터니언을 쓰는 이유 : 오일러 앵글에서 일어나는 짐벌락이 일어나지 않기 때문.
크기 조절
1.
void Update(){
if(Input.GetKey(KeyCode.W)){
this.transform.localScale = this.transform.localScale + new Vector3(2,2,2) * Time.deltaTime;
}
}
w를 누르면 1초에 2배씩 커짐.
< 유용한 메서드 >
this.transform.forward = new Vector3(0,0,1)
this.transform.up = new Vector3(0,1,0)
this.transform.right = new Vector3(1,0,0)
앞의 것을 뒤의 것처럼 쓸 수 있음
[SerializeField]
private GameObject go_camera;
void Update(){
if(Input.GetKey(KeyCode.W)){
this.transform.LookAt(go.camera.transform.position);
}
}
w를 누르면 위의 스크립트를 가진 오브젝트가 카메라(go_camera)를 바라보는 코드
[SerializeField]
private GameObject go_camera;
void Update(){
transform.RotateAround(go_camera.transform.position, Vector3.up, 100 * Time.deltaTime);
}
카메라(go_camera)를 중심으로 1초에 100도씩 빙글빙글 회전하는 코드