看起来很简单吧?
GameObject towers = GameObject.Find("towers");
GameObject ball = GameObject.Find ("ball");
foreach (Transform tower in towers.transform) {
Vector3 heading = ball.transform.position - tower.position;
float distance = heading.magnitude;
Vector3 direction = heading.normalized;
Vector3 newDir = Vector3.RotateTowards(ball.transform.position, heading, 1, 0.0F);
tower.rotation = Quaternion.LookRotation(newDir);
//Debug.DrawRay(ball.transform.position, newDir, Color.red);
}
结果如下:
后面的塔楼很不错但是前面的方向是错误的。发生了什么?另外,有没有办法控制塔架弯曲的程度,这取决于从球到塔架的距离?
答案 0 :(得分:2)
这是一个解决方案,它使用AnimationCurve根据它们与你的球之间的距离来控制你的塔的旋转角度。
我的动画曲线有两个键:
public AnimationCurve effect;
private GameObject towers ;
private GameObject ball ;
private void Start()
{
towers = GameObject.Find("towers");
ball = GameObject.Find ("ball");
}
private void Update()
{
foreach (Transform tower in towers.transform)
{
Vector3 direction = (ball.position - tower.position);
Vector3 rotationAxis = Vector3.Cross( direction.normalized, Vector3.up );
float angle = effect.Evaluate( direction.magnitude ) ;
tower.rotation = Quaternion.AngleAxis( angle, rotationAxis );
// If you want your towers to look at your ball :
// tower.rotation = Quaternion.LookRotation( direction ) * Quaternion.Euler( -angle, 0, 0 );
}
}