Sunday, October 11, 2015

unity - Move rigidbody using WASD keys but rotate it based on camera/mouse movement


I am very new to unity and my scripts are based on some scripts found on the web.


I want to make a first person view so the camera is attached to my rigidbodys head. Then i want to move my rigidbody based on keyboard input (wasd) and rotate it using the mouse movement.


Until now, i used the following code for moving my rigidbody:


void Update() {

/* calculate rigidbody movement */

movement = new Vector3( Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;

/* calculate mouse look to rotate the rigidbody*/
mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, mouseDelta.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, mouseDelta.y, 1f / smoothing);
mouseLook += smoothV;

}


void FixedUpdate() {

/* apply rigidbody movement from Update() */
transform.Translate( movement * moveSpeed * Time.deltaTime );
/* apply rigidbody rotation from Update() */
transform.localRotation = Quaternion.AngleAxis(mouseLook.x, transform.up);
/* apply camera rotation from Update() */
Camera.main.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);


}

I learned today that i dont have to move a rigidbody's transform but now i am totally confused and it seems i have to restart my whole (first!) project.


So when i use MovePosition and MoveRotation, how do i rotate it based on the camera perspective/mouse movement?


I think the movement Vector is ok so i can simply rewrite the FixedUpdate to something like


rigidbody.MovePosition(movement * speed * Time.deltaTime)

but i am totally stuck on how to apply the camera rotation to my rigidbody to use it like


void FixedUpdate() { 
/* move the rigidbody */

rigidbody.MovePosition(movement * moveSpeed * Time.deltaTime);
/* rotate the camera */
camera.transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);

/* but how can i rotate the rigidbody based on the cameras rotation??? */
rigidbody.MoveRotation(?????);

}

I hope its clear what i want, thank you!





No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...