简体   繁体   中英

Unity C#: Issue with rotating, now facing wrong direction

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;
}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM