Rigidbody刚体组件控制物体的移动和旋转

Unity中如果一个物体有Rigidbody组件,可以通过Rigidbody组件控制该物体移动和旋转

Rigidbody.position

Rigidbody.rotation

void Start()
    {
        //设置游戏物体的位置及旋转
        GetComponent().position = Vector3.zero;
        GetComponent().rotation = Quaternion.identity;
    }

Rigidbody.MovePosition()

void Update()
    {
        //控制物体移动
        GetComponent().MovePosition(transform.position + transform.forward * Time.deltaTime);     
    }

Rigidbody.MoveRotation()

    public Transform target;//要面向的目标物体
    public float speed = 1f;

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent();
    }

    void Update()
    {        
        //控制物体旋转
        //得到一个由当前物体指向目标物体的向量
        Vector3 direction = target.position - transform.position;
        direction.y = 0;
        Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
        //通过刚体组件让物体朝向目标物体
        rb.MoveRotation(Quaternion.Slerp(rb.rotation,
            targetRotation, Time.deltaTime * speed));
    }

Rigidbody.AddForce()

    public float thrust;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent();
    }

    void Update()
    {
        //在物体正前方添加一个力
        rb.AddForce(transform.forward * thrust,ForceMode.Force);
        //rb.AddForce(new Vector3(0, 0, 1));
    }

 

你可能感兴趣的:(Unity基础)