[英]How do I point a gameobject towards another one, while it's rotating around a moving player?
Im making a space exploration game and I'm trying to have an arrow rotating around the player, pointing towards the sun in the center of the level.我正在制作一款太空探索游戏,我试图让一个箭头围绕玩家旋转,指向关卡中心的太阳。 This is to make the game more readable.
这是为了让游戏更具可读性。 The "arrow" is for now just a cylinder with a sphere on it - with the sphere representing the arrow point.
“箭头”现在只是一个上面有球体的圆柱体——球体代表箭头点。 The rotation around the player is working, but I can't get it to point towards the sun, consistently.
围绕玩家的旋转正在起作用,但我无法让它始终指向太阳。 As seen in the image here, the arrow is pointing almost opposite of where I want it to.
如图所示,箭头指向的方向几乎与我想要的方向相反。
The code I'm using is as follows我使用的代码如下
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);
In addition to Quaternion.FromToRotation I have also tried using LookAt, which also gave me weird results.除了 Quaternion.FromToRotation 之外,我还尝试使用 LookAt,这也给了我奇怪的结果。 (I tried all the different up directions, ie LookAt(sun, Vector3.left) and (sun, Vector3.back), etc. Hoping some clever minds can help. Thanks in advance.
(我尝试了所有不同的向上方向,即LookAt(sun,Vector3.left)和(sun,Vector3.back)等。希望一些聪明的头脑可以提供帮助。提前致谢。
Theory理论
You can use您可以使用
Quaternion.FormToRotation
四元数.FormToRotation
It create a quaternion (thing who handle the rotation of your gameobject) by giving a direction vector and the "0" vector.它通过提供方向向量和“0”向量来创建四元数(处理游戏对象旋转的东西)。 With these informations it'll know how to rotate your transform.
有了这些信息,它就会知道如何旋转你的变换。
Exemple例子
I would do something like:我会做类似的事情:
Vector3 direction = sunPos - playerPos;
transform.rotation = Quaternion.FromToRotation(direction, Vector3.right);
Vector3.right = (1f,0f,0f) and you should use the standard direction of your arrow. Vector3.right = (1f,0f,0f) 并且您应该使用箭头的标准方向。 For exemple if when arrow have no rotation it point up (0f,1f,0f), you should use Vector3.up insteed.
例如,如果当箭头没有旋转时它指向上方 (0f,1f,0f),您应该使用 Vector3.up insteed。
As I said on comment you don't need raycast for this.正如我在评论中所说,您不需要光线投射。 (Maybe you need it later on your code)
(也许您稍后在代码中需要它)
Vector3 delta = sunPos - playerPos;
Vector3 direction = delta.normalized;
float distance = delta.magnitude;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.