Unity对象围绕力场弯曲

时间:2018-01-15 17:16:47

标签: unity3d rotation

我希望在下面的图片中看到塔楼受到力场的影响。 collapse

看起来很简单吧?

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);
}

结果如下:

collapse result

后面的塔楼很不错但是前面的方向是错误的。发生了什么?另外,有没有办法控制塔架弯曲的程度,这取决于从球到塔架的距离?

1 个答案:

答案 0 :(得分:2)

这是一个解决方案,它使用AnimationCurve根据它们与你的球之间的距离来控制你的塔的旋转角度。

我的动画曲线有两个键:

  1. (0,90)//意味着当球离球0个单位时,塔将旋转90°
  2. (10,0)//意味着当距离球10个单位时,塔将旋转0°
  3. 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 );
        }
    }