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

How do you move a parent object based on the angle of one of the children?

Discussion in 'Physics' started by adogsjunkmail, Sep 21, 2020.

  1. adogsjunkmail

    adogsjunkmail

    Joined:
    Sep 12, 2020
    Posts:
    22
    In the game I'm currently making, the key mechanic is that you can angle the player to jump at an angle. The player has a parent object whose angle doesn't change accept for left and right, so that the angle of the player doesn't change the direction the player moves when walking around. I just can't get the parent to move at the angle of it's child for the jump, but not move at the angle for walking. Is there a way to do this? (it's in 3D btw, and I'm using a rigidbody for the parent, but it doesn't need to be a rigidbody)
     
  2. rubcc95

    rubcc95

    Joined:
    Dec 27, 2019
    Posts:
    222
    I think you don't need a parent and a child for that purpose. Rigidbody has 2 functions called AddForce and AddRelativeForce.

    For a movement in world horizontal axis just use AddForce (it will add the force regardeless of the rotation).
    For a jump in the current angle, use AddRelativeForce. and it will do the movement taking the rotation into account.
     
  3. adogsjunkmail

    adogsjunkmail

    Joined:
    Sep 12, 2020
    Posts:
    22
    Thanks but, I need the parent because like most FPS' the parents movement is relative to its rotation on the horizontal axis. If I used AddRelativeForce, than W,A,S,D would represent North East South, and West, instead of forward, left, backward, right, which could be tricky to control. I guess that would work as a last resort though. sorry I didn't mention it was a FPS.
     
    rubcc95 likes this.
  4. rubcc95

    rubcc95

    Joined:
    Dec 27, 2019
    Posts:
    222
    Well, to be honest I did not understood what do you mean about North East... but anyway, if you need a parent with a rb2d and the character as a child, you can refer the child transform and add a force like this:

    Code (CSharp):
    1. public class ParentController : MonoBehaviour
    2. {
    3.     Transform child;
    4.     Rigidbody rb;
    5.     [SerializeField] float force;
    6.  
    7.     void Jump() => rb.AddForce(child.rotation * Vector3.up * force, ForceMode.Impulse);  
    8. }
    child.rotation * Vector3.up gives you Vector3.up if child has no rotation, Vector3.down if child is face down, etc. So you add a force, not relative force in the Y axis of your child.
     
  5. adogsjunkmail

    adogsjunkmail

    Joined:
    Sep 12, 2020
    Posts:
    22
    That has just worked. Thank you so much!