標籤:
這裡給主相機綁定一個指令碼。
指令碼寫為:
using UnityEngine;using System.Collections;public class camerafollow : MonoBehaviour { //主攝像機跟隨主角一起移動 public float xMargin = 1f; public float yMargin = 1f; public float xSmooth = 8f; public float ySmooth = 8f; public Vector2 maxXandY; public Vector2 minXandY;// Use this for initialization private Transform player;void Start () {
//這裡獲得是綁定的主角,需要一起跟隨移動,就要獲得主角的屬性 player = GameObject.FindGameObjectWithTag("pk_0").transform; maxXandY.x = 10; maxXandY.y = 10;} bool checkxmargin() { return Mathf.Abs(transform.position.x - player.position.x) > xMargin; } bool checkymargin() { return Mathf.Abs(transform.position.y - player.position.y) > yMargin; }// Update is called once per framevoid Update () { Trackplayer();} //跟蹤主角 void Trackplayer() { float targetx = transform.position.x; float targety = transform.position.y; if (checkxmargin()) { targetx = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime); } if (checkymargin()) { targety = Mathf.Lerp(transform.position.y, player.position.y, xSmooth * Time.deltaTime); } targetx = Mathf.Clamp(targetx, minXandY.x, maxXandY.y); targety = Mathf.Clamp(targety, minXandY.y, maxXandY.y); transform.position = new Vector3(targetx, targety,transform.position.z); }}
:
Unity3D 相機跟隨主角移動