Unity(4)
Unity(4) RigidBody 추가와 player의 움직임 구현
Rigidbody:
Unity자체 물리엔진 컴포넌트이다. 중력의 영향, 속도부여, 충돌 등을 가능하게 한다.
- collider(충돌체):
- 충돌이 일어나기 위해 필요한 boundary를 결정하는 컴포넌트
- 다양한 형태 가능, Mesh에 따라 결정가능
- IsTrigger옵션, 닿았는지 알수 있게 해주는 옵션
RigidBody를 player에 추가해보기.
player(sphere)클릭 -> inpector창에 add component클릭 ->Rigidbody 검색하여 추가.
Use Gravity가 켜져있는지 확인하고 실행하면, 공이 밑으로 떨어지는 걸 볼수 있음.
Hierarchy창에서 우클릭후 cube생성 후, 이름 floor로 변경. cube를 바닥처럼 보이게 크기 설정.
위와 같이 설정 후 공의 움직임 보기.
Rigidbody의 구성요소:
- Mass: object의 질량
- Drag: 공기 저항, 0이면 저항없음, 무한이면 즉시 멈춤
- Angular Drag: 회전시 공기저항
- Use Gravity: 중력의 영향을 받을지
- Is Kinematic: Object가 물리엔진이 아니라 Transform으로만 조작되게 함, 조작 시에 물리 법칙이 적용되지는 않기를 원할 때 사용할 수 있다.
- Interpolate: 어색한 움직임을 보일 때 개선하는 기능
- Collision Detection: 빠르게 움직이는 오브젝트가 충돌의 감지 없이 다른 오브젝트를 지나쳐 가는 것을 방지
- Constraints: 움직임 제약, Position or Rotation을 제어.
player 움직임 개선 코드:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private Rigidbody rigid;
// Start is called before the first frame update
void Start()
{
rigid = GetComponent<Rigidbody>(); //내컴포넌트에서 Rigidbody가져오기기
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal");//좌우 방향키
float v = Input.GetAxisRaw("Vertical"); //상하 방향키
rigid.AddForce(new Vector3(h,0,v) * speed, ForceMode.Impulse); // rigidbody에 힘을 전해주는 함수
}
}
위에 코드로 player를 방향키 방향으로 밀어주는 듯한 움직임 구현. 공이 굴러감.
Player 점프 구현:
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
31
32
33
34
35
36
37
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float jumpPower;//inspector창에서 숫자 바꿔주기
bool isJump; //현재 점프 상대흫 나타내는 boolean, 땅에 닿고 있으면 false
private Rigidbody rigid;
// Start is called before the first frame update
void Start()
{
isJump = false;
rigid = GetComponent<Rigidbody>(); //내컴포넌트에서 Rigidbody가져오기기
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal");//좌우 방향키
float v = Input.GetAxisRaw("Vertical"); //상하 방향키
rigid.AddForce(new Vector3(h,0,v) * speed, ForceMode.Impulse);// rigidbody에 힘을 전해주는 함수
if(Input.GetKeyDown(KeyCode.Space) && !isJump){
isJump = true;
rigid.AddForce(new Vector3(0,jumpPower,0), ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision other){
if(other.gameObject.name == "floor"){ //floor를 만나면 isjump를 false로 바꿔줘 다시 점프가능하게 하기.
isJump = false;
}
}
}
위의 코드를 통해 점프키(스페이스바)를 눌렀을 때 점프 가능.
jumpPower나 speed는 inpector창에서 숫자를 바꿔가며 원하는 감도를 찾는다.
감사합니다.
This post is licensed under CC BY 4.0 by the author.