- Home /
Centric gravity issues...
'allo, I'm trying to finish this gravity system, but the character never wants to be attracted to my game object. Instead, it keeps getting attracted to the world origin. Here are the segments in question:
public GameObject centricGravityTarget;
else if (gravityMode == 2) {
if (Physics.Raycast((transform.position + transform.up),(centricGravityTarget.transform.position + transform.position).normalized * -1, out hit, gravityField, groundLayers.value)) {
desiredUp = (centricGravityTarget.transform.position + transform.position).normalized;
}
}
else if (gravityMode == 2) {
Vector3 gravityDir = centricGravityTarget.transform.position + transform.position;
gravityDir = gravityDir.normalized;
rigidbody.AddForce(gravityDir * -gravity * rigidbody.mass);
}
I suspect that the former will work once the latter works.
Thanks!
Answer by Peter G · Jun 11, 2010 at 08:59 PM
Ok, your problem with both appears to be you are adding/subtracting backwards for what you are trying to accomplish.
For the first one, I had a little trouble figuring out exactly what you are doing, I think you are sending a ray towards the planet to get the normal so that you can align the rotation correctly. So here is what I came up with. The trick is to subtract the player's position from the attractor instead of add them and flip the sign. Think of it like this. 5 - 2 != -(5 + 2)
RaycastHit hit;
if (Physics.Raycast((transform.position + transform.up),(centricGravityTarget.transform.position - transform.position).normalized, out hit)) {
desiredUp = hit.normal;
print (desiredUp);
}
The second one had a nearly identical problem. So here it goes.
//subtract instead of add and multiply by positive gravity in the last step.
Vector3 gravityDir = centricGravityTarget.transform.position - transform.position;
gravityDir = gravityDir.normalized;
rigidbody.AddForce(gravityDir * gravity * rigidbody.mass);
One physics side note that I might be completely off on, so if I am, sorry, but don't objects fall at different speeds based on drag, not mass. Because don't heavier objects fall at the same speed as lighter ones (drop two balls outside to test it). If my understanding of physics is utterly wrong :) , please "save" me.
This worked perfectly! I can't believe I missed something so simple. But hey, I guess that's how things work, eh?
Thanks a bunch! Just a little scripting to blend planet weights together, and my platformer system will be complete.
And yes, it's based on drag. The reason it's multiplied by mass is because it takes more force to move heavier objects. It's the same in real-world physics. With more massive objects, it takes more force to move it. And those objects have more mass by which to be affected by gravity.