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. Dismiss Notice

Move a rigid body forward localy

Discussion in 'Physics' started by azfboom, Mar 3, 2022.

  1. azfboom

    azfboom

    Joined:
    Aug 19, 2018
    Posts:
    1
    Hello,
    I am working on a small project where I have a battleram.
    I managed to control it as an arcade car so it can move around the map.
    Now I want to move the timber inside it backward and forward but I do not manage to keep the timber to move only along the local z axis.
    Either it works only in initial position and then when my vehicle move it does not keep the loca z axis as its move orientation, either it gets inertia when I move the vehicle.
    I am started to get lost with all the local vs global Vector3.

    My idea was to do something like this :
    //rb : timber's rigid body
    if (Input.GetKey(KeyCode.LeftAlt))
    {
    rb.MovePosition(rb.transform.localPosition - rb.transform.forward * speed * Time.fixedDeltaTime );

    }
    rb.velocity = Vector3.zero; // Remove inertia
    But with that, my timber teleport far from the ram.

    Any help would be appreciated.

    Regards.
     

    Attached Files:

  2. r31o

    r31o

    Joined:
    Jul 29, 2021
    Posts:
    460
    Why
    transform.localPosition - transform.forward?

    If you want to move something in the local z axis try with just transform.forward and then multiply it by the speed.

    Also watch out with rigidbody.movePosition afaik it ignores collision, so you can get inside walls.
     
  3. SkylorBeck

    SkylorBeck

    Joined:
    Aug 29, 2020
    Posts:
    13
    MovePosition does not do this.
    https://docs.unity3d.com/ScriptReference/Rigidbody-position.html

    "If you want to continuously move a rigidbody use MovePosition instead, which takes interpolation into account."