Hello, I am trying to make a rigidbody controller, I got the camera working and rotating the player fine.
However I have been unable to get the formula for the direction to move the player left/right/back/forward depending on the direction the camera/player.
This line is closest that works, but if I look up in the sky with the camera, player will fly in the sky on Y axis and I dont want that.
rb.velocity = Camera.main.transform.forward * ms * Time.deltaTime;
I tried other formulas, but they didn’t work. I will appreciate all help.
I do this nowadays by treating the move input as a vector in the camera’s local space.
Vector2 moveInput = /* something */
Vector3 moveInput3D = new Vector3(moveInput.x, 0, moveInput.y); // make it into a vec3
Vector3 worldMove = Camera.main.transform.TransformVector(moveInput3D); // convert it to world-space
Vector3 move = Vector3.ProjectOnPlane(worldMove, Vector3.up); // get rid of any resulting vertical component
move *= worldMove.magnitude / move.magnitude; // compensate for the reduction in length
I always wind up doing the rotation the wrong way around. This way isn’t exactly trivial, but I like it
I tried your way first, it works for forward and backwards, - Vector3.up and Vector3.down, however when I tried to add movement for left and right, the other vectors do not work properly and unity even comes with error if I try to use Vector3.right etc. Do you have any idea how to fix that?
Kurt, I did look at your script, even in Visual studio, but was unable to decode it, I am still a learning programmer, also got about 10 errors in there and not sure why, seems to be missing namespaces.
moveInput3D = new Vector3(horizontal, 0, vertical); // make it into a vec3
Vector3 worldMove = Camera.main.transform.TransformVector(moveInput3D); // convert it to world-space
Vector3 move = Vector3.ProjectOnPlane(worldMove, Vector3.down); // get rid of any resulting vertical component
move *= worldMove.magnitude / move.magnitude; // compensate for the reduction in length
rb.velocity = move * ms * Time.deltaTime;
Vector3.down used here for backwards movement, and Vector3.up was for forwards movement. It seems to work fine ingame. But any other vectors do not work and result in random errors ingame.
Edit again: hmm did i miss something about the way its supposed to handle movement, because I usually dont use the horizontal axis etc.
Another Edit: I was testing the directions and the most simple line worked, just used normal Vector3(0,0, 1) etc. and i was trying out some hardcore directions, I never thought this was going to work, but somehow magically it works and detects the direction where the player faces. Hm. Those vectors…