[Unity] Rigidbody의 속성과 메서드

https://www.youtube.com/watch?v=V1ZcL55h3h4&list=PLUZ5gNInsv_PR72-V9bTABaZu2py4DJq8&index=3 

위 영상을 바탕으로 작성하였습니다.

 


 

Edit - Project Settings - Physics

 

Mass : 질량

Drag : 공기저항

Angular Drag : 회전물체에 대한 저항

Use Gravity : 중력

Is Kinematic : 체크하면 물리 효과 없어짐

Interpolate : 캐릭터의 움직임이 부자연스러울 때 자연스럽게 만들기 위해 쓴다.

Collision Detection : 총알같이 빠른 물체 충돌 감지에 쓴다.

Freeze Position : 위치 고정

Freeze Rotation : 회전 고정

 

< 많이 쓰는 속성 >

private Rigidbody myRigid;

void Start(){
	myRigid = GetComponent<Rigidbody>();
}

void Update(){
	if(Input.GetKey(KeyCode.W)){
    	// 속도 조절
    	myRigid.velocity = Vector3.forward; // 1초에 z축 방향으로 1씩 이동
        myRigid.angularVelocity = -Vector3.right; // x축을 기준으로 (-1,0,0)으로 회전
        
        // 질량값 바꾸기
        myRigid.mass = 2f;
        
        // 저항값 바꾸기
        myRigid.drag = 2f;
        
        // 최대 회전속도 바꾸기
        myRigid.maxAngularVelocity = 100;
    }
}

이런식으로 리지드바디의 속성들을 스크립트에서 쓸 수 있다.

 

< 유용한 메서드 >

private Rigidbody myRigid;
private Vector3 rotation;

void Start(){
	myRigid = GetComponent<Rigidbody>();
    rotation = this.transform.eulerAngles;
}

void Update(){
	if(Input.GetKey(KeyCode.W)){
    	// 이동
    	myRigid.MovePosition(transform.forward * Time.deltaTime); // 앞으로 이동
        
        // 회전
        rotation += new Vector3(90,0,0) * Time.deltaTime;
        myRigid.MoveRotation(Quaternion.Euler(rotation));
        
        // 근데 MovePosition, MoveRotation은 관성과 질량에 영향을 안 받음
        // 관성과 질량에 영향 받게 하고 싶으면 AddForce
        myRigid.AddForce(Vector3.forward);
        
        // 회전력이 남아있게 회전시킬 때
        myRigid.AddTorque(Vector3.up); // y축 기준으로 회전
        
        // 폭발할 때 유용한 메서드
        myRigid.AddExplosionForce(10,this.transform.right, 10); // 오른쪽폭발로 인해 왼쪽으로 날아감
        // Add~로 시작하는 메서드는 모두 물리 효과랑 관련되어 있음
        
    }
}