Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to stop object from moving after calling transform.Translate()

Discussion in 'Scripting' started by OOVUM, Sep 17, 2022.

  1. OOVUM

    OOVUM

    Joined:
    Mar 8, 2020
    Posts:
    17
    Hello, in my game I need a car to stop moving after it contacts my player, but no matter what I try to the car wont stop moving forward and pushing forward. Help on this issue would be greatly appreciated


    public class CarMovement : MonoBehaviour
    {
    float speed = 5f;
    bool shouldMove = true;

    private void Update()
    {
    if (shouldMove == true)
    {
    transform.Translate(new Vector3(0, 0, speed) * Time.deltaTime);
    }
    }
    private void OnCollisionEnter(Collision col)
    {
    if (col.gameObject.name == "Player")
    {
    transform.Translate(new Vector3(0, 0, 0));
    shouldMove = false;
    }
    }
    }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,006
    I would first check with a
    Debug.Log
    that
    OnCollisionEnter
    is actually being called in the first place. And if it is, another one after your first if statement to see if its indeed registering whether it hits the player.
     
    OOVUM likes this.
  3. OOVUM

    OOVUM

    Joined:
    Mar 8, 2020
    Posts:
    17
    thanks for the quick reply, I happened to test it out and the if statement is working but OnCollisonEnter is not being called. How do I fix this?
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,006
    Last edited: Sep 17, 2022
    OOVUM likes this.
  5. OOVUM

    OOVUM

    Joined:
    Mar 8, 2020
    Posts:
    17
    I didn't read that carefully enough the last time, thanks for your help. Turns out that OnCollisionEnter only works if one of the objects has a non-kinematic rigidbody. This is weird since my player is using a character controller and the car was simply moving through transform.Translate(), yet OnCollsionEnter worked successfully for the player. I ended up slapping on a rigid body to the car and checked all the contraints so the script would work.
     
    spiney199 likes this.