I’m trying to create a rotation system using Rigidbodies and this implementation is working when the “orbiting” object is initially stationary
private void RotateAroundObject()
{
//Thrust
// Get the direction from the player to the center object
Vector2 toCenter = (transform.position - player.transform.position).normalized;
// Calculate the desired velocity for a circular orbit
Vector2 desiredVelocity = Vector2.Perpendicular(toCenter) * Mathf.Sqrt(Physics2D.gravity.magnitude * radius / toCenter.magnitude);
// Calculate the force to achieve the desired velocity (assuming mass is 1 for simplicity)
Vector2 force = (desiredVelocity - rb.velocity) * rb.mass / Time.fixedDeltaTime;
// Apply the force to the player's rigidbody over time
rb.AddForce(force, ForceMode2D.Force);
//Rotation
// Determine the direction of travel
Vector2 directionOfTravel = rb.velocity.normalized;
// Calculate the angle in degrees that the player should be rotated
float angle = Mathf.Atan2(directionOfTravel.y, directionOfTravel.x) * Mathf.Rad2Deg;
// Set the rotation of the player
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
}
(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
9ljzeb
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