简体   繁体   中英

Can't update rigidbody in Unity2D with C#

There's an object that the player can spawn. It should go from the player to wherever the mouse is clicked. To find out the angle that it should move, it needs to know the player's position. But, no matter where the player goes, it still thinks the position stays at (-1, 2.4), which is where the player is spawned, messing up all of the calculations. Is there a way to let the script know where the player is currently?

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

Ok, I found an answer. I was using the prefab to get the position instead of the object currently on the scene. To get the object on the scene, all I had to do was use GameObject.Find().

i think your player is prefab and you are trying to acess positions in prefabs try this. var Object = GameObject.FindObjectOfType();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM