- Home /
How do I do rigidbody.velocity while ignoring one axis?
Hey! I have made a first person shooter controller using rigidbody.velocity. The x and z movement is fine, but when I add a force to the y axis to jump, the character teleports upward, and slowly glides down.
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float speed = 500f;
public float jumpPower = 10f;
void Update()
{
if(Input.GetKey(KeyCode.Space) && Physics.Raycast(transform.position, Vector3.down, 1.05f))
{
GetComponent<Rigidbody>().AddForce(0f, jumpPower, 0f);
}
GetComponent<Rigidbody>().velocity = transform.TransformDirection(Vector3.forward)*(Input.GetAxis("Vertical")*speed*Time.deltaTime) + transform.TransformDirection(Vector3.right)*(Input.GetAxis("Horizontal")*speed*Time.deltaTime);
}
}
This happens because rigidbody.velocity sets the y velocity to 0 constantly. To solve this, I need the rigidbody.velocity line to ignore changing the y velocity. I tried using this method,
rigidbody.velocity = new Vector3(~~~, rigidbody.velocity.y, ~~~))
This doesn't work. If you have anything on this, please tell me. Thanks a lot!
EDIT: The, + new Vector3(0f, jump, 0f), in the rigidbody.velocity isn't supposed to be there. Accidentally left that in when I was trying some things. ;p
Your answer
![](https://koobas.hobune.stream/wayback/20220612182027im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting a RigidBody's velocity messes with my custom gravity, not sure how to proceed. 0 Answers
Any way to gracefully detach object with Unity physics? 2 Answers
Moving rigidbody (Player) with addForce or Velocity ? 1 Answer
Rigidbody.velocity seems to be breaking jumping physics 0 Answers
VR Sword Physics, how to add force or velocity to the sword for impact when it hits an object 1 Answer