본문 바로가기

유니티/유니티 엔진

[유니티] GetComponent, AddForce

728x90
반응형

AddForce

 

Rigidbody 컴포넌트에는 AddForce 라는 이벤트함수가 내장되어 있다.

 

AddFroce 메서드의 기능은 좌표를 입력받으면 해당하는 좌표의 값과 방으로 오브젝트에 힘을 가한다.

 

이 오브젝트를 스크립트에서 사용하기 위해서는 GetComponent 함수를 사용하여 컴포넌트를 불러와야 한다.

 

void Update()
{
    if (Input.GetKeyDown(KeyCode.LeftAlt))
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 500));
}

 

 

 

 

 

 

이 때 Rigidbody2D 를 여러 번 호출할 것을 예상하여 컴포넌트를 미리 불러오는 것도 가능하다.

 

public class PlayerMove : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Rigidbody2D My = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftAlt))
            My.AddForce(new Vector2(0, 500));
    }
}

 

728x90
반응형