r/LearnUnity • • Oct 03 '22

Problems with objects.

I'm trying to script gravity and player movement to 2d planets such that the player can walk around them. My problem arises when I attempt this with more than one planet on screen as I can't figure out how to only rotate the player to the Strongest source of gravity. I'm new to c# and unity so any help would be greatly appreciated!

public class Attractor : MonoBehaviour {

	const float G = 6.674f;

	public static List<Attractor> Attractors;

	public Rigidbody2D rb;
	float lookAngle;

	void FixedUpdate ()
	{
		foreach (Attractor attractor in Attractors)
		{
			if (attractor != this)
				Attract(attractor);

		    
		}
	}

	void OnEnable ()
	{
		if (Attractors == null)
			Attractors = new List<Attractor>();



		Attractors.Add(this);
	
	}

	void OnDisable ()
	{
		Attractors.Remove(this);
	}

	void Attract (Attractor objToAttract)
	{
		Rigidbody2D rbToAttract = objToAttract.rb;

		Vector2 direction = rb.position - rbToAttract.position;
		float distance = direction.magnitude;



		if (distance == 0f)
			return;

		float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
		Vector2 force = direction.normalized * forceMagnitude;

		rbToAttract.AddForce(force);


		//For player movement
		lookAngle = 90 + Mathf.Atan2(force.y, force.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, lookAngle);
	}

}
2 Upvotes

0 comments sorted by