Add Force To One Object in Relation to the Rotation of Another Object (C#)

My player has a GameObject which contains everything (we’ll call it ‘Player’), a head that rotates with mouse input, and a body that Lerps to align with the y axis of the head’s rotation (this also contains other things such as weapons).

The ‘Player’ GameObject cannot rotate due to the body needing to be able to Lerp to the head. If ‘Player’ rotates with the head it cancels out the Lerp of the body.

To move ‘Player’ I’m using GetComponent().AddRelativeForce(velocityChange, ForceMode.VelocityChange);.

The issue I’m having is that because ‘Player’ does not rotate, and the AddRelativeForce() method is running on it, ‘Player’ doesn’t move in directions relative to where the head is looking.

Here is the script as it is (moving ‘Player’, not in relation to head rotation):

void PlayerWalk()
    {
        //Set Target Velocity to be forward(1) or back(-1)

        //assign vector to horizontal (left/right) and vertical (forward/back) inputs 
        Vector3 targetVelocity = new Vector3(hInput, 0, vInput);

        targetVelocity = transform.TransformDirection(targetVelocity);
        targetVelocity *= movementSpeed;
        Vector3 velocityChange = targetVelocity - GetComponent<Rigidbody>().velocity;
        GetComponent<Rigidbody>().AddRelativeForce(velocityChange, ForceMode.VelocityChange);

    }

How do I adjust this to account for the head’s y rotation so that when I want to move forward it adds force in the direction the head is looking?

Here are also some pictures to potentially give a better understanding of the situation:

81743-player-heirarchy.jpg

Ok, let’s do some changes to that script you have there:

 //Asign your head object on inspector or do a find()
    public GameObject head;

    void PlayerWalk()
    {
      //Just this. transform.forward will always set the next vector values to wherever your object is looking  
        Vector3 velocityChange = head.transform.forward * movementSpeed;
        GetComponent<Rigidbody>().AddRelativeForce(velocityChange, ForceMode.VelocityChange);
    }

I don’t know how your input works so that’s a general idea.

Some Input code that could work:

if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.ArrowUp))
{
  PlayerWalk();
}