您的位置:首页 > 移动开发 > Unity3D

Unity物体跟随脚本

2015-01-06 10:55 393 查看
using UnityEngine;

using System.Collections;

public class demo : MonoBehaviour

{

//跟随目标

public Transform TargetObj = null;

//平滑速度,使用线性差值运算使跟随者平滑的移动到目标位置

public float SmoothSpeed = 3;

//设置最高点

public bool UseMaxHeight = false;

//最高点

public float MaxHeight = 0;

//设置最低点

public bool UseMinHeight = false;

//最低点

public float MinHeight = 0;

//初始时与跟随对象的相对距离

private Vector3 initDis;

void Awake()

{

if (TargetObj == null)

{

throw new UnityException("The TargetObj can't be null!");

}

initDis = new Vector3(this.transform.position.x - TargetObj.position.x,

this.transform.position.y - TargetObj.position.y,

this.transform.position.z - TargetObj.position.z);

}

void Start()

{

//检查最大高度和最小高度的合法性

if (UseMaxHeight && UseMinHeight)

{

if (MaxHeight <= MinHeight)

{

throw new UnityException("The MaxHeight must larger than MinHeight!");

}

}

}

// Update is called once per frame

void Update()

{

float zValue = TargetObj.position.z + this.initDis.z;

if (UseMaxHeight && zValue > MaxHeight)

{

zValue = MaxHeight;

}

if (UseMinHeight && zValue < MinHeight)

{

zValue = MinHeight;

}

Vector3 targetPos = new Vector3(TargetObj.position.x + this.initDis.x,

TargetObj.position.y + this.initDis.y,

zValue);

this.transform.position = Vector3.Lerp(this.transform.position,

targetPos,

this.SmoothSpeed);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: