C# Can';t使用C更新Unity2D中的刚体#

C# Can';t使用C更新Unity2D中的刚体#,c#,unity3d,object,C#,Unity3d,Object,玩家可以生成一个对象。它应该从播放器移动到鼠标单击的任何位置。为了找出它应该移动的角度,它需要知道玩家的位置。但是,不管玩家去哪里,它仍然认为位置保持在(-1,2.4),这是玩家产生的地方,把所有的计算都搞乱了。有没有办法让脚本知道玩家当前在哪里 using UnityEngine; public class plosionSelfScript : MonoBehaviour { // Start is called before the first frame update p

玩家可以生成一个对象。它应该从播放器移动到鼠标单击的任何位置。为了找出它应该移动的角度,它需要知道玩家的位置。但是,不管玩家去哪里,它仍然认为位置保持在(-1,2.4),这是玩家产生的地方,把所有的计算都搞乱了。有没有办法让脚本知道玩家当前在哪里

using UnityEngine;

public class plosionSelfScript : MonoBehaviour {
    // Start is called before the first frame update
   public GameObject player;
   public Camera cam;
   private Rigidbody2D playerRB;
   public Rigidbody2D plosionRB;
   float xVel;
   float yVel;
   Vector2 finalPos;
   Vector2 distanceNeeded;
   float hypo;

   void Start() {
        cam = Camera.main;
        playerRB = player.GetComponent<Rigidbody2D>();
        finalPos = cam.ScreenToWorldPoint(Input.mousePosition);
        Vector2 dir = finalPos - playerRB.position;
        float angle = Mathf.Atan2(dir.y, dir.x);
        yVel = 10 * Mathf.Sin(angle);
        xVel = 10 * Mathf.Cos(angle);
        plosionRB.velocity = new Vector2(xVel, yVel);
        Debug.Log(finalPos);
        Debug.Log(playerRB.position);
        Debug.Log(dir);
        Debug.Log(angle);
   }

   void Update() {
        playerRB = player.GetComponent<Rigidbody2D>();
   }
}

使用UnityEngine;
公共类plosionSelfScript:单行为{
//在第一帧更新之前调用Start
公共游戏对象玩家;
公共摄像机;
私人刚体2D播放器B;
公共刚体2d plosionRB;
浮动xVel;
伊维尔;
向量2终末;
需要向量2距离;
浮球;
void Start(){
cam=Camera.main;
playerRB=player.GetComponent();
finalPos=cam.Screen到世界点(输入.mousePosition);
Vector2 dir=最终版本-播放器位置;
浮动角度=数学Atan2(方向y,方向x);
yVel=10*Mathf.Sin(角度);
xVel=10*Mathf.Cos(角度);
plosionRB.velocity=新矢量2(xVel,yVel);
Debug.Log(finalPos);
Debug.Log(playerRB.position);
Log(dir);
调试日志(角度);
}
无效更新(){
playerRB=player.GetComponent();
}
}

好的,我找到了答案。我使用预置来获取位置,而不是当前场景中的对象。要在场景中获取对象,我所要做的就是使用GameObject.Find()。

我认为您的玩家是预制的,您正在尝试访问预制中的位置试试这个。
var Object=GameObject.FindObjectOfType()

请标出答案:)