I want to make a platformer with the style of Angry Birds Space’s great outerspace physics. To do this, I need to make a planet sprite have a gravitational force. To do this, I added a CircleCollider2D
, which has a RigidBody2D
I can alter. How can I add gravitational attraction to this object’s RigidBody2D
? C# code examples would be appeciated.
for simple simulation try this
public GameObject planet; // assign your planet GO in unity editor here
public float gravityFactor = 1f; // then tune this value in editor too
void FixedUpdate(){
rigidbody.AddForce((planet.transform.position - transform.position).normalized * rigidbody.mass * gravityFactor / (planet.transform.position - transform.position).sqrMagnitude);
}
You need to calculate the direction components, normalize them and then add a force to that vector, whose strength is defined by the inverse-square law:
var intensity = 5.5f;
components = transform.position.planet - transform.position.ship;
comp_normalized = components / components.magnitude;
force = comp_normalized * (intensity * (1 / Vector2.Distance(from, end)))
rigidbody2D.addForce(force);
Play around with intensity, to suit your needs. (I don’t know C#, sorry.)
Something like a central force? Something like this maybe, but I´m not sure what you mean:
Transform worldCenter;
private readonly static float gravity = 0.1f;
void Update(){
AddGravitationalForce();
}
void AddGravitationalForce(){
Vector3 force = (transform.position - worldCenter.position)
force = force.normalized/force.sqrMagnitude;
force *= gravity*Time.deltaTime;
rigidbody2D.AddForce(new Vector2(force.x, force.y));
}