使用“ RotateAround”可以进行“ LookAt”目标转换吗?

时间:2019-01-08 12:42:50

标签: c# unity3d

我的场景中有一个“球”,一个“射击方向”和一个“中心目标”。如图所示,“射击方向”是“球”游戏对象的子代。我可以使用Unity内置的“ RotateAround”方法在“球”周围旋转“射击方向”。

https://imgur.com/a/FifaNOr

我想要实现的是;

  1. 使用Unity内置的“ RotateAround”方法在“球”周围旋转“射击方向”。
  2. 保持“射击方向”在不顾“球”的位置和旋转的情况下注视着“中心目标”。
  3. 在进行数字1和2时,请勿更改“球”自身的旋转。

到目前为止,我在“射击方向”游戏对象附带的ShootDirection.cs中拥有的内容:

    void FixedUpdate () {
        if (canRotate && rotationSpeed != 0f) {
            RotateAroundCenter ();
            LookAtCenter ();
        }
    }

    public void SetDistanceFromCenter () {
        //Set distance from the Ball's Vector3.zero
        thisTransform.localPosition = thisTransform.localPosition.normalized * distanceFromCenter;
    }

   public void LookAtCenter () {
        //Look at the Ball's Vector3.zero
        Vector3 dir = Vector3.zero - thisTransform.localPosition;
        float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
        thisTransform.rotation = Quaternion.AngleAxis (angle + 90, Vector3.forward);
    }

   public void RotateAroundCenter () {
        thisTransform.RotateAround (rotateAroundTransform.position, Vector3.back, rotationSpeed * Time.fixedDeltaTime * rotationDirection);
   }

2 个答案:

答案 0 :(得分:0)

这应该给你一个向量distanceToBall,使其远离球并指向centerTarget

public void LookAtCenter () {
    this.Transform.position = Vector3.MoveTowards(ball, centerTarget, -distanceToBall)
}

答案 1 :(得分:0)

根据@ colin-young的回答,我可以达到预期的效果。

Expected and achieved behaviour can be seen here

    void FixedUpdate () {
        RotateTowardsTarget (LevelManager.Instance.CurrentLevel.GetPlayer ().centerTarget.transform);
        LookAtCenter ();
    }

    public void LookAtCenter () {
        //Look at the Ball's Vector3.zero
        Vector3 dir = Vector3.zero - thisTransform.localPosition;
        float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
        thisTransform.rotation = Quaternion.AngleAxis (angle + 90, Vector3.forward);
    }

    public void RotateTowardsTarget (Transform targetTransform) {
        if (targetTransform != null) {
            thisTransform.position = Vector3.MoveTowards (rotateAroundTransform.position, targetTransform.position, distanceFromCenter);
        }
        LookAtCenter ();
    }