问题描述
我正在做一个太空探索游戏,我试图让箭头绕着玩家旋转,指向关卡中心的太阳。这是为了使游戏更具可读性。 目前,“箭头”只是一个圆柱体,上面有一个球体-球体代表箭头。播放器周围的旋转正在起作用,但始终无法使它指向太阳。如图所示,箭头指向的位置几乎与我想要的相反。
我正在使用的代码如下
playerPos = transform.position;
sunPos = sun.transform.position;
// Cast ray from player to sun
Ray ray = new Ray(playerPos,sunPos - playerPos);
RaycastHit hitInfo;
if (Physics.Raycast(ray,out hitInfo,400,mask))
Debug.DrawLine(ray.origin,sunPos,Color.green);
Debug.Log("distance" + hitInfo.distance);
// Rotate arrow around player.
arrow.transform.position = playerPos + ray.direction.normalized*2;
// Point arrow towards sun. This is not working
arrow.transform.rotation = Quaternion.FromToRotation(gameObject.transform.position,sunPos);
除了Quaternion.FromToRotation外,我还尝试使用LookAt,这也给了我奇怪的结果。 (我尝试了所有不同的向上方向,即LookAt(sun,Vector3.left)和(sun,Vector3.back)等。 希望一些聪明的人能有所帮助。预先感谢。
解决方法
理论
您可以使用
Quaternion.FormToRotation
它通过提供方向矢量和“ 0”矢量来创建四元数(处理游戏对象旋转的事物)。有了这些信息,它将知道如何旋转变换。
示例
我会做类似的事情:
Vector3 direction = sunPos - playerPos;
transform.rotation = Quaternion.FromToRotation(direction,Vector3.right);
Vector3.right =(1f,0f,0f),您应该使用箭头的标准方向。例如,如果箭头没有旋转,则箭头指向上(0f,1f,0f),则应使用Vector3.up insteed。
正如我在评论中说的那样,您不需要进行射线广播。 (也许您稍后会在代码中使用它)
Vector3 delta = sunPos - playerPos;
Vector3 direction = delta.normalized;
float distance = delta.magnitude;