- Home /
Cannot Jump or fall while while moving?
Hello, all. I have been working on making my player character jump, and he jumps fine as long as he is not moving. If he is moving, however, ie I am pressing the keys to move him, he slowly ascends, seemingly ignoring gravity or the amount of force the Rigidbody added until I stop pressing the keys and he descends as desired. After I make him jump while idling, I can make him stay in the air by walking around, which is also undesirable. I don't recall ever experiencing this before.
Here's a section of the code so far.
public class PlayerScript : MonoBehaviour
{
public Animator Anim;
public Rigidbody RBody;
public float speed = 3f;
public float horizontalSpeed = 2.0f;
public float verticalSpeed = 2.0f;
public float jumpForce = 2.0f;
public Vector3 jump;
void Update()
{
float h = horizontalSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h, 0);
transform.Translate(0, 0, speed * Input.GetAxis("Vertical") * Time.deltaTime);
Anim.SetFloat("speed", Input.GetAxis("Vertical"));
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
void Jump()
{
jump = new Vector3(0.0f, 2.0f, 0.0f);
RBody.AddForce(jump * jumpForce, ForceMode.Impulse);
}
transform.Translate(0, 0, speed * Input.GetAxis("Vertical") * Time.deltaTime);
With this line, you're telling it to stay in the same posisiton with the exception of your vertical input. If you want physics to be applied, stop overriding it by using transform to move your gameObject.
Answer by Pathojen · Nov 11, 2021 at 11:37 PM
Whoa...easier than I thought. Just add the jump function before the move function, apparently. It works like a charm.
void Update()
{
if (Input.GetButtonDown("Jump") && isGrounded == true)
{
Jump();
}
//MovePlayer();
}
Answer by swanne · Nov 10, 2021 at 09:29 PM
Hey,
Get rid of the Vector3 jump.
Replace your Jump() function with this
void Jump()
{
RBody.AddForce(0.0f, jumpForce, 0.0f, ForceMode.Force);
}
Had trouble with the code but finally got it working. Trouble is it does exactly what $$anonymous$$e does. I will keep digging for answers.
Your answer
Follow this Question
Related Questions
Throwing a Spear 1 Answer
Grappling hook springjoint 0 Answers
How can I add smooth movement to a RigidBody? 2 Answers
Calculate Angular Velocity to Match Remote Position 0 Answers
How to move player on a moving vehicle 0 Answers