I am building my first 3D game right now. As movement is almost working fine now, there are still two things that I can’t figure out how to improve.
- As I hit “W” and “D” at the same time my Rigidbody should move diagonal. But instead it’s moving only in the direction I hit last.
- I want my rigidbody to jump in the direction it is facing after turning
left
(orright
). Instead it’s always jumping in the same global direction.
This is my code:
public class PlayerMovement : MonoBehaviour {
public float moveSpeed;
public float jumpPower;
public float turningSpeed;
public Rigidbody rb;
public Transform groundCheck;
public float groundRadius;
public LayerMask whatIsGround;
void Start ()
{
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate ()
{
if (Physics.CheckSphere (groundCheck.position, groundRadius, whatIsGround)) {
if(Input.GetKey(KeyCode.W))
rb.MovePosition(transform.position + transform.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.S))
rb.MovePosition(transform.position - transform.forward * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.D))
rb.MovePosition(transform.position + transform.right * moveSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.A))
rb.MovePosition(transform.position - transform.right * moveSpeed * Time.deltaTime);
if (Input.GetKeyDown (KeyCode.Space)) {
rb.AddForce (Vector3.up * jumpPower, ForceMode.Impulse);
rb.AddForce (Vector3.forward * jumpPower, ForceMode.Impulse);
}
}
if(Input.GetKey(KeyCode.E))
transform.Rotate(Vector3.up * turningSpeed * Time.deltaTime);
if(Input.GetKey(KeyCode.Q))
transform.Rotate(Vector3.down * turningSpeed * Time.deltaTime);
}
}
I would appreciate some help