简体   繁体   中英

How to track transform.position in real time?

I'm working on a little 2d game where you control a planet to dodge incoming asteroids. I'm implementing gravity in the following manner:

public class Gravity : MonoBehaviour
{
 Rigidbody2D rb;

 Vector2 lookDirection;

 float lookAngle;

 [Header ("Gravity")]
 
 // Distance where gravity works
 [Range(0.0f, 1000.0f)]
 public float maxGravDist = 150.0f;
 
 // Gravity force
 [Range(0.0f, 1000.0f)]
 public float maxGravity = 150.0f;
 
 // Your planet
 public GameObject planet;

 void Start()
 {
     rb = GetComponent<Rigidbody2D>();
 }

 void Update()
 {   
     // Distance to the planet
     float dist = Vector3.Distance(planet.transform.position, transform.position);

     // Gravity
     Vector3 v = planet.transform.position - transform.position;
     rb.AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity);

     // Rotating to the planet
     lookDirection = planet.transform.position - transform.position;
     lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;

     transform.rotation = Quaternion.Euler(0f, 0f, lookAngle);  
 }
}

The problem is that the asteroids are attracted to the initial spawn point of the planet (0,0), it doesn't update in real time with the movement of the planet. So if I move the planet to the corner of the screen, the asteroids are still attracted to the centre of it.

Is there a way to solve this?

Thank you very much and excuse any flagrant errors!

There are 2 ways to get to an object with speed:

  1. get the object to the player and in each update just use the planet.transform.position

  2. using look at first to rotate to the plant and then using vector3.forword as the direction of the movement.

The first solution doesn't work for you so you might want to try the second one.

any way, if your lookAt part doesn't work too you can use

 Vector3 dir = target.position - transform.position;
 float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
 transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

or

Vector3 targetPos = target.transform.position;
 Vector3 targetPosFlattened = new Vector3(targetPos.x, targetPos.y, 0);
 transform.LookAt(targetPosFlattened);

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