1
votes

I have a character/rigidbody and 'she' can turn around. When I press Play in Unity, if I move forward/backward, that's fine, she moves forward/backward. It's a good start.

But then if I turn her left or right, then go forward/backward, she now moves sideways.

She is a rigidbody component set as a parent in the scene.

Surely it's not difficult to do, but I can't figure out how to set her rotation so that when she turns, she will move 'forward' when I press the button to move her forward! There are plenty of first-person-shooter games where you can turn and move 'forward' and the player goes in the correct direction.

My rotation script at the moment is this:

Vector3 EulerAngleVelocity;
public float rotateSpeed = 250.0f;

void Update() {
    if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow))
    {
        MoveVector = PoolInput();
        Move();
    }

    if (Input.GetKey(KeyCode.RightArrow))
    {
        EulerAngleVelocity = new Vector3(0, rotateSpeed, 0);
        Quaternion deltaRotation = Quaternion.Euler(EulerAngleVelocity * Time.deltaTime);
        rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
    }
}

private void Move()
{
    rigidbody.AddForce((MoveVector * moveSpeed));
}

private Vector3 PoolInput()
{
    Vector3 dir = Vector3.zero;

    dir.x = joystick.Horizontal();
    dir.z = joystick.Vertical();

    if (dir.magnitude > 1)
        dir.Normalize();

    return dir;
}
2
How about splitting the orientations of the rigidbody (your velocity vector - where your character moves) versus where the 'head' of the character looks (your look rotation)? You can rotate one with your input, and rotate the other by Alt+input for example. This, of course, assumes you have a movable 'head' mesh or first look / third person camera. - Varaquilex
Unfortunately I don't have that option. The character is ready-made from the Asset Store and is all in one piece :( - JaceG
Need to see the movement code also. - Immersive
I've updated my first post to include the movement code :) - JaceG

2 Answers

5
votes

You're moving your joystick and adding that direction in relation to the WORLD instead of in relation to your player. If you want to add force relative to the orientation of the RigidBody probably what you want to use is rigidBody.AddRelativeForce (documentation) instead of simply rigidBody.AddForce.

1
votes

Your problem isn't your rotation code, it's your movement code. You're applying a motion in world-space, not local-space ('object'-space).

For example, if you're using Vector3.Forward, you will want to use transform.Forward instead.