# Question RigidBody2D and Rotations

Discussion in 'Physics' started by Tamar_, Jan 20, 2024.

1. ### Tamar_

Joined:
Jan 29, 2021
Posts:
3
I'm trying to create a rotation system using Rigidbodies and this implementation is working when the "orbiting" object is initially stationary

Code (CSharp):
1.     private void RotateAroundObject()
2.     {
3.         //Thrust
4.         // Get the direction from the player to the center object
5.         Vector2 toCenter = (transform.position - player.transform.position).normalized;
6.         // Calculate the desired velocity for a circular orbit
7.         Vector2 desiredVelocity = Vector2.Perpendicular(toCenter) * Mathf.Sqrt(Physics2D.gravity.magnitude * radius / toCenter.magnitude);
8.         // Calculate the force to achieve the desired velocity (assuming mass is 1 for simplicity)
9.         Vector2 force = (desiredVelocity - rb.velocity) * rb.mass / Time.fixedDeltaTime;
10.         // Apply the force to the player's rigidbody over time
12.
13.         //Rotation
14.         // Determine the direction of travel
15.         Vector2 directionOfTravel = rb.velocity.normalized;
16.         // Calculate the angle in degrees that the player should be rotated
17.         float angle = Mathf.Atan2(directionOfTravel.y, directionOfTravel.x) * Mathf.Rad2Deg;
18.         // Set the rotation of the player
19.         player.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle - 90)); // Subtracting 90 degrees to align the 'up' direction of the sprite with the direction of travel
20.     }
(Thank you GPT)

The problem is, when I introduce some velocity before entering the '"gravity field" of the gravity object.
I do this by attaching a circle collider onto another object, with it set to act as a trigger to start this behavior.

The issue now is that on entering the trigger, the player object is deflected away as seen here

I don't know what the best approach to allow my object to begin orbiting new gravity objects it interacts with with an initial velocity.

Thanks

### Unity Technologies

Joined:
May 24, 2013
Posts:
11,657
You're not rotating the Rigidbody2D using physics; you're stomping over the Transform so when the physics eventually runs, it's having to read the Transform and instantly update the Rigidbody2D rotation. Then physics tries to work then you stomp over the rotation again.

Don't ever write to the Transform, that's the role of the Rigidbody2D.