using System.Collections; using System.Collections.Generic; using UnityEngine; //Author:ZCG //CreatTime:12/1/2017 /// ///物体伸缩(梯子,举臂等) /// public class ObjStretch: MonoBehaviour { private void Start() { Init(); initY = objUp[0].localPosition.y;//初始化第一节高度 } private void Update() { InputControl(); } /// /// 初始化 /// protected virtual void Init() { } /// /// 输入控制 /// protected virtual void InputControl() { if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W)) Stretch(); if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.S)) Shorten(); } /// /// 根据物体名字关键字获取可伸展的所有物体 /// /// protected Transform[] GetObj(string keyword) { List childs = new List(); for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); if (child.name.Contains(keyword)) { childs.Add(child); } } return childs.ToArray(); } [Tooltip("可以伸展的所有物体(不包括固定的那一节)")] /// /// 可以伸展的所有梯子(不包括固定的那一节) /// public Transform[] objUp; private Vector3 speedVec = new Vector3(0, 1, 0); [Tooltip("每一节米数")] public float nodeLength; [Tooltip("速度")] public float speed; private float initY; //第几节索引 private int index = 0; /// /// 延伸 /// protected virtual void Stretch() { //根据高度计算操作的第几节 if (objUp[index].localPosition.y < (index+1) * nodeLength) { for (int i = index; i < objUp.Length; i++)//所有节一起移动 objUp[i].localPosition += speed * Time.deltaTime * speedVec; } else if(index < objUp.Length - 1) { index++; Stretch(); } } /// /// 收回 /// protected virtual void Shorten() { //当前节是否已经伸展 if (objUp[index].localPosition.y > initY) { for (int i = index; i < objUp.Length; i++)//移动每一节阶梯 objUp[i].localPosition -= speed * Time.deltaTime * speedVec; } //如果这一节移动完开始移动下一节 if (index > 0 && objUp[index].localPosition.y <= objUp[index - 1].localPosition.y) { index--; Shorten(); } } }