我有一个脚本,使用Unity引擎的lerp
功能处理游戏对象的翻译。
public class MovePiece : MonoBehaviour {
Vector3 startPoint;
Vector3 endPoint;
float speed = 1;
float startTime;
float journeyLength;
void Start() {
startPoint = gameObject.GetComponent<Transform>().position;
endPoint = startPoint + new Vector3(20, 0, 0); //Will make this a variable eventually
startTime = Time.time;
journeyLength = Vector3.Distance(startPoint, endPoint);
}
void Update() {
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(startPoint, endPoint, fracJourney);
}
}
但是,我只希望在我点击一个游戏对象时运行一次,然后在它完成移动时从该对象中分离出来,以便下次单击另一个对象时可以再次运行它。
我有一个连接到相机的光线投射设置,允许我选择游戏对象,我只是不知道我如何在所选对象上运行此脚本!
我该怎么做?
答案 0 :(得分:4)
重命名您的Start方法
void Start() { ... }
到其他组件可公开访问的内容,即:
public void BeginMove() { ... }
然后,让您的Raycast脚本调用您的新函数。您需要访问被点击的GameObject的MovePiece组件:
...
GameObject hitObject = raycastHit.collider.gameObject;
MovePiece hitObjectMovePiece = hitObject.getComponent<MovePiece>();
hitObjectMovePiece.BeginMove();
您可能还想为动画引入布尔锁。这是您的代码可能是什么样的。
public class MovePiece : MonoBehaviour {
Vector3 startPoint;
Vector3 endPoint;
float speed = 1;
float startTime;
float journeyLength;
// Animation lock
private bool moving = false;
public void BeginMove() {
startPoint = gameObject.GetComponent<Transform>().position;
endPoint = startPoint + new Vector3(20, 0, 0); //Will make this a variable eventually
startTime = Time.time;
journeyLength = Vector3.Distance(startPoint, endPoint);
moving = true;
}
void Update() {
if(!moving)
return;
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(startPoint, endPoint, fracJourney);
if(fracJourney >= 1.0f)
moving = false;
}
}
我希望有所帮助!祝你好运。