unity3D 物體跟隨移動

//腳本掛載移動的物體上

public class Player : MonoBehaviour {
public float Speed = 4;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    float h = Input.GetAxis("Horizontal");
    transform.Translate(Vector3.right * h * Speed * Time.deltaTime, Space.World);

    float v = Input.GetAxis("Vertical");
    transform.Translate(Vector3.forward * v * Speed * Time.deltaTime, Space.World);
    
}

private void OnTriggerEnter(Collider other)
{
    switch (other.tag) {
        case "Sphere":
          other.GetComponent<pet>().enabled = true;
           // Destroy(gameObject);
            break;

        default:
            break;

    }
    
}

}
//Tag 換成Sphere
在這裏插入圖片描述

//腳本掛載跟隨的物體上
//打開腳本是跟隨移動 關閉是觸發移動
// public Transform target; 把移動的物體拖上

public class pet : MonoBehaviour {

//寶寶跟隨的目標
public Transform target;
//寶寶跟隨目標的偏移量
public Vector3 offset;
// Use this for initialization
void Start()
{

}
// Update is called once per frame
void Update()
{
   // Debug.Log(Vector3.Lerp(new Vector3(0, 0, 0), new Vector3(0, 0, 10), Time.deltaTime));
}
void LateUpdate()
{
    offset = target.forward * -2 + target.up * 2;
    transform.position = Vector3.Lerp(transform.position, target.position + offset, Time.deltaTime);
    transform.rotation = target.rotation;
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章