I’m a freshman in college majoring in Game Design, and for my programming class we are required to update a previous Maze project to allow two players.
My maze was too small for two players on one track, so I am making two mazes and rotating them to be where the “walls” would be. My problem now is making a player run along the walls with the same gravity horizontally as would be on the ground.
I added
GetComponent<Rigidbody>().AddForce(Vector2.left * 9.8f);
But this does nothing but allow me to roll alongside the bottom wall.
I’ve seen the answer to this on 2D games, but not yet on 3D. Thanks, Brandon.
As a baseline, the gravity in Unity is applied to rigidbodies something like this:
// C#
void FixedUpdate()
{
rigidbody.AddForce(Physics.gravity, ForceMode.Acceleration);
}
So, every physics update, the objects with rigidbodies are pushed in the direction of gravity (default Vector3(0, -9.81, 0)). ForceMode.Acceleration ignores the mass of the object while pushing it, as gravity naturally would, and scales it relative to the FixedUpdate() rate.
With this in mind, there are two possible ways to approach this:
1 - If your gameplay environment is limited to a single wall for all players, you can simply modify Physics.gravity in the editor or by script to push them in the same direction.
2 - If the players are separated and each need their own gravitational force applied, you’ll want each to have their own script for customized gravity application.
As a simplified example of what would go into that:
// C#
public Vector3 gravityDirection; // The direction of gravity for the object this script is attached to
Rigidbody rb; // This just keeps things simple
void Start()
{
rb = gameObject.GetComponent<Rigidbody>();
rb.useGravity = false; // Don't use world gravity, since we're replacing that for this object.
}
void FixedUpdate()
{
rb.AddForce(gravityDirection, ForceMode.Acceleration);
}