Rigidbody velocity in direction facing
Hi Guys,
I'm trying to set a rigidbody velocity from Input.GetAxis. I've tried the following which has the correct movement:
float mH = Input.GetAxis("Horizontal");
float mV = Input.GetAxis("Vertical");
_rb.velocity = new Vector3 (mH * speed, _rb.velocity.y, mV * speed);
However I need it to move in direction the object is facing. I can do this with:
float mV = Input.GetAxis("Vertical");
_rb.velocity = transform.forward * (mV * speed);
But I also need it to work Horizontally also. Any input on this would be greatly appreciated!
Answer by kadenathompson · Jan 06, 2021 at 04:45 AM
It's actually quite a simple thing to do. You can simply add the transfrom.forward and the transfrom.right before multiplying extra values like speed. Additionally you ought to multiply everything by Time.deltaTime to avoid having frame drops affect the movement speeds.
float mV = Input.GetAxis("Vertical");
float mH = Input.GetAxis("Horizontal");
_rb.velocity = (transform.forward * mV + transform.right * mH).normalized * speed * Time.deltaTime;
Changes:
.normalized prevents whatever it is your moving from moving fast diagonally Time.deltaTime makes the movement framerate independent ie. the movement speed won't change if the framerate does
Answer by meatkare · Jan 10 at 09:55 AM
@kadenathompson well your above code needs a little modification cause ofcourse it solves one problem but it will also show up another new problem which is the y axis, as you are constantly setting the y-axis it will affect the movements on y axis like falling and jumping so to solve you have to add rb.velocity.y on y axis like this
float move_x=Input.GetAxis("Horizontal");
float move_z=Input.GetAxis("Vertical");
Vector3 Up=new Vector3(0f,rb.velocity.y,0f);
rb.velocity=(transform.forward * move_z + transform.right * move_x).normalized*speed+Up;
I hope this helps :)