I'm working in a project with Unity 2d where player walks on a small planet. I try to use some code from youtube tutorial to apply gravity to my planet.This code consists of two parts, Attractable and Attractor. Attractables are used on objects that are drawn and Attractors placed on planets. When I try to play it it works, but when my player is idle, my player get pull toward the bottom of the planet.
in Attractor script, it just find all object inside Circle area with Physics2D.OverlapCircleAll
and then call Attract function from object with Attractable script. The Attractor code look like this:
void Update()
{
SetAttractedObjects();
}
void FixedUpdate()
{
AttractObjects();
}
void SetAttractedObjects()
{
AttractedObjects = Physics2D.OverlapCircleAll(planetTransform.position, effectionRadius, AttractionLayer).ToList();// can be optimized
}
void AttractObjects()
{
for (int i = 0; i < AttractedObjects.Count; i++)
{
AttractedObjects[i].GetComponent<Attractable>().Attract(this);
}
}
And inside the Attractable script, it has Attract function, that apply some force to object rigidbody. This is the function called from the previous Attractor script. This code apply force from rigidbody position to the position of the planet.
public void Attract(Attractor artgra)
{
Vector2 attractionDir = (Vector2)artgra.planetTransform.position - m_rigdibody.position;
m_rigdibody.AddForce(attractionDir.normalized * -artgra.gravity * force * Time.fixedDeltaTime);
if (currentAttractor == null)
{
currentAttractor = artgra;
}
}
This script also has, a RotateToCenter function which ensures the player is always facing the planet. This function is called from the Update function.
void RotateToCenter()
{
Vector2 distanceVector = (Vector2)currentAttractor.planetTransform.position - (Vector2)m_transform.position;
float angle = Mathf.Atan2(distanceVector.y, distanceVector.x) * Mathf.Rad2Deg;
m_transform.rotation = Quaternion.AngleAxis(angle + 90,Vector3.forward);
}
I try to use Debug.DrawLine
to see the AttractionDir variable from Attract function, and i get:
I think it's the correct force vector because it applies the force from my player position to the center of my planet the way I want it. But my player always move a bit to the bottom of the planet. I tried to remove my RotateToCenter function, and my player doesn't pull down anymore, but it also causes my player to not move as it should. I try to reduce the force, but my player still moved. So i try to increse the force and my player moves faster. I get confused, because i think the force direction is from my player rigidbody position to the planet center(it should only pull my player to the planet not moved it), so why my player moved by this force. I also set rigidbody gravity to 0 so it doesn't effect my player but i still get the small movement. Why is this happening? Anyone know how to solve it?