Hello Everyone. I wanted to create a physics based movement for my character.
[Header("Movement")]
public float playerSpeed;
public float jumpForce;
[HideInInspector]
public Rigidbody rb;
Vector3 x, z;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
//-----Inputs-----//
x = transform.right * Input.GetAxisRaw("Horizontal");
z = transform.forward * Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown(KeyCode.Space))
Jump();
}
void FixedUpdate()
{
Movement();
}
void Movement()
{
Vector3 movement = (x + z).normalized * playerSpeed;
rb.AddForce(movement);
}
void Jump()
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
I know I can use rb.velocity to set velocity but I also want to add force to the player from certain direction when certain key is pressed. The issue with rb.velocity is that when I am adding force with the movement key pressed the force is canceled as velocity is being overwrite.
Thats why I want to add force. If you have other method to solve this problem I will be grateful.
Thanks for reading.