I'm new to this, I'm making an obstacle dodging game, and part of the losing conditions is that if the player object falls below -1 on the y axis then the player loses the game, but every time I run the game and intentionally go off the edge of the ground, the player object just floats. I've double checked that the Rigidbody for the player uses gravity, and even checked my scripts for logic errors, nothing has worked. got any ideas on how to fix it?
I've already added the code rb.useGravity = true;
here's the script for the player's movement: `
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody rb;
public float ForwardMomentum = 1000f
public float SidewaysMomentum = 500f
void FixedUpdate()
{
rb.useGravity = true;
rb.AddForce(0, 0, FowardMomentum * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (Input.GetKey("a"))
{
rb.AddForce(-SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
To make a reproducible example for this, all you need to do is:
- Add a cube game object (I believe that the box collider and mesh renderer should already be loaded in there)
- Add the Rigidbody component and tick use gravity (As well as ticking freeze rotation on the x axis)
- Add the new script with the code from above (please fix any errors you find to make it work and let me know how you did it :D)
- Add a ground floor and just make it so the player cube is sitting on top of it
- then just run it a couple of times and see how it goes, if nothing is out of the ordinary then idk what's going on with my unity
CodePudding user response:
In unity using Rigidbodies is sometimes a bit difficult. But the solutions to these problems come pretty easily.
-Firstly Check if you even have applied a rigidbody (mostlikely you do else your game wouldn't run)
-Check if you have accidently selected "IsKinematic" which could cause your gravity not to be used on that rigidbody.
-Check the way you get the rigidbody in your script, if the script is correctly applied to your gameobject. (if the rigidbody is gotten via the inspector you might need to just drag and drop it into the script)
-Check the collider on your ground if it isn't bigger then the visual