Minbutt
Minbutt

Reputation: 89

Gravity/Physics not working in Unity game

I am following Brackey's tutorial on how to create a simple 3D game in Unity (https://www.youtube.com/watch?v=D4I0I3QJAvc&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6&index=8&ab_channel=Brackeys) however I can't seem to get the physics/gravity (rigid body?) to work properly. It was previously working on my main character (the cube) until I added in more grey cubes to be obstacles in a level. All gravity stopped and everything now begins to float into the air when the play button is pressed.

objects floating away

player is selected so you can see rigid body settings

^Player is selected so you can see rigid body settings.

New Behaviour 2 script:

using UnityEngine;

public class NewBehaviour2 : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewaysForce = 500f;
    // Start is called before the first frame update


    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if (Input.GetKey("d"))
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
    }
}

FollowPlayer script:

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{


    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;
    }
}

Player Collision script:


using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
        }
        
    }

}

Please let me know if you need any more photos. Thank you.

Upvotes: 0

Views: 1085

Answers (1)

Congobill
Congobill

Reputation: 83

You should use TriggerCollider for the grey boxes (just check the trigger option on the collider component), as they don't need gravity and they only trigger an action (Game Over I suppose). Then the script of the grey box should be changed to:

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnTriggerEnter (Collider collisionInfo)
    {
        if (collisionInfo.tag == "Obstacle")
        {
            movement.enabled = false;
        }
        
    }

}

Upvotes: 0

Related Questions