- Home /
Question by
Grabthesky · Jul 15, 2018 at 02:49 PM ·
3dplayer movement
Player movement 3D hack n Slash problems
I need to make a player movement depending of camera rotation, i can move forward from camera rotation but i have problems with the lateral movement and the character rotation to his direction.
public class PlayerController : MonoBehaviour
{
public Camera cam;
public float speedMove;
private Vector3 camForward, movement;
private float forwardMove, horizontalMove;
void Start () {
}
void Update () {
camForward = cam.transform.forward;
forwardMove = Input.GetAxis("Vertical");
horizontalMove = Input.GetAxis("Horizontal");
camForward.y = 0;
print(camForward);
if (forwardMove != 0)
{
movement = camForward * forwardMove;
}
if (horizontalMove != 0)
{
transform.Translate(Vector3.right * horizontalMove * Time.deltaTime * speedMove, Space.Self);
}
transform.Translate(movement * speedMove * Time.deltaTime);
}
}
This is the idea: 
movement-player.png
(110.1 kB)
Comment
Answer by JVene · Jul 15, 2018 at 06:04 PM
@Grabthesky, I'd suggest orienting a direction vector to that of the camera. Something like (untested code, off the top of my head proposal):
camForward = cam.transform.forward;
forwardMove = Input.GetAxis("Vertical");
horizontalMove = Input.GetAxis("Horizontal");
camForward.z = 0;
// camForward is now only the x/y orientation of the camera,
// ignoring pitch,
// calculate the angle
float camAngle = Vector3.Angle( Vector3.zero, camForward );
Quaternion q = Quaternion.Euler( 0, 0, camAngle );
// q is now a quaternion representing a Z axis rotation of the camera angle
Vector3 inputDir = new Vector3( forwardMove, horizontalMove, 0 );
// inputDir is a world space vector incorporating mouse input in the x/y plane
inputDir = q * inputDir;
// inputDir is now rotated by the camera angle, making the mouse controls camera oriented
// and can now be applied, with speed and deltaTime as the direction intended.
Or at least until the 3rd coffee kicks in that's what I think.
this is 3d , so the y axis is the perpeticular to the ground, i want to move forward over the ground, on your script tha player moves up on pressing forwrd and on the x axes pressing latera(horizontal).
Your answer