简体   繁体   中英

Trouble rotating vector inside unity

I'm making a game where you rotate your player and change gravity. the problem im having is to do with actually putting the rotation of the player, the keyboard inputs of the player and the current gravity together.

Line 1(Quaternion.FromToRotation) works completely fine until gravity is down(gravityDir(0, -1, 0)) or up(gravityDir(0, 1, 0)) and in that case the y component of movementInput will be inverted.

I can't just check if its one of the two and flip it back because I need it to be able to gradually change from one value to the other or otherwise be in between a different angle(like (1, 1, 0) for instance)

movementInput is just wasd put into a vector(ws being x, ad being z).

gravityDir is a vector for gravity(0, -1, 0) for down (0, 1, 0) being up (1, 0, 0) being positive x direction etc.

headAttach is a GameObject that controls the players head, I'm getting its y value in the code to rotate the movementInput vector so I can "move in the direction i'm facing".

movementInput = Quaternion.FromToRotation(gravityDir, Vector3.up) * movementInput;
movementInput = Quaternion.AngleAxis(headAttach.transform.localRotation.eulerAngles.y, transform.up) * movementInput;

rb.AddForce(movementInput * 5 * movementSpeed);

Don't use FromToRotation in this case, because you care about more than the direction of up. You also care about the directions of forward/right.

Instead, use LookRotation . You need to find the closest direction to the direction that the player is looking at (I assume that's headAttach.transform.forward ) which is perpindicular to the direction of gravity. You can use cross products for that. Then, use that direction for the forward parameter of LookRotation and the direction opposite gravity for up:

Vector3 movementInput = Vector3.forward * Input.GetAxis("Vertical") 
        + Vector3.right * Input.GetAxis("Horizontal");

Vector3 upDir = -gravityDir;
Vector3 lookDir = headAttach.transform.forward;

Vector3 rightDir = Vector3.Cross(upDir, lookDir);
Vector3 forwardDir = Vector3.Cross(rightDir, upDir);

movementInput = Quaternion.LookRotation(forwardDir, upDir) * movementInput;

rb.AddForce(movementInput * 5 * movementSpeed);

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