- Home /
Adding a force to RigidBody2d - Velocity returns 0
I'e been working on making a type of planetary gravity in my 2D game. I've made a center of gravity, and attached this script to the RigidBody2D that's supposed to be attracted to this center. I've removed the ability for this RididBody2D to use the natural gravity from the Physics Engine.
//The gravity centre
public Transform ring;
public float gravityStrength;
Rigidbody2D myRB;
void Start()
{
myRB = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
attract();
}
void attract()
{
//Pulling the object down
Vector3 downDirection = (transform.position - ring.position).normalized;
myRB.AddForce(downDirection * gravityStrength);
Debug.Log(myRB.velocity);
//Keeping the object upright
Quaternion targetRotation = Quaternion.FromToRotation(transform.up, downDirection) * transform.rotation;
transform.rotation = targetRotation;
}
However, for some reason, the object doesn't seem to accelerate when it falls towards this centre of gravity (which is also slow for some reason), which isn't very realistic for gravity. I want to fix this acceleration issue, but I can't even debug the velocity of the rigidbody. It return 0 all the time. Any idea why?
Answer by N1warhead · Mar 01, 2017 at 09:31 AM
I'm going to assume it has to deal with your Vector3 downDirection not working good with your addforce.
From what you're explaining it's sounding like you want it to sorta work like a blackhole, the player falls towards the ring. Which if that's the case you can do an inverse explosive force. (Just google "Unity Explosive Force") and just change the value to a negative number, so instead of blowing the player outward you can give it a suction like force that gravitationally tries to pull it to an object.
It's technically a Vector3, but you can just leave the Z axis at 0 or where-ever you have them at. E.G. Vector3(SomePos,SomePos,0);
Do you think there's a way to make it like a constant acceleration toward the point ins$$anonymous$$d (more or less like real gravity)? I plan to add jumping mechanics.
It should be a constant force, so long as your player is within the boundaries of the trigger. That's how I made my one game I made awhile back... If the player go within the range of the suction it would constantly try to pull you into the center of the (ring) for your case. So if you want it constant just make sure the the player is within the range of it and it will be constant as if it were gravity.