- Home /
Jump only sometimes works and player doesn't always jump high?
My script is supposed to be making sure that my player can jump whenever it touches the floor, however it doesn't always jump when it's touching the floor. Also, sometimes when it jumps, it jumps and sometimes it jumps really low. Can anyone help fix this problem? I really want my player to be able to jump consistently.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Ball_Movement : MonoBehaviour {
public string moveHorizontal = "Horizontal";
public float moveSpeed;
// public float runSpeed;
public float walkSpeed;
public float jump;
public int jumpTime;
public float rotateSpeed = 10f;
public bool onFloor = true;
Rigidbody rb;
// public float maxJumpHeight;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
// maxJumpHeight = 2f;
}
// Update is called once per frame
void Update() {
if (Input.GetKey(KeyCode.LeftShift)) {
moveSpeed = walkSpeed * 3;
}
else {
moveSpeed = walkSpeed;
}
/* if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
transform.Rotate(rotateSpeed, 0, 0);
} */
float lrAxis = Input.GetAxis(moveHorizontal);
if (lrAxis != 0.0f) {
rb.MovePosition(rb.position + rb.rotation * Vector3.right * moveSpeed * Time.fixedDeltaTime * lrAxis);
transform.Rotate(rotateSpeed, 0, 0);
}
if (onFloor = true && (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)))
{
if (jumpTime != 2)
{
rb.AddForce(transform.up * jump, ForceMode.Impulse);
jumpTime += 1;
}
else
{
onFloor = false;
}
}
// if (rb.velocity.y >= maxJumpHeight) {
// rb.velocity = Vector3.zero;
// }
}
void OnCollisionEnter(Collision other)
{
if (other.transform.CompareTag("Floor"))
{
onFloor = true;
jumpTime = 0;
}
if (other.transform.CompareTag("Respawn")) {
SceneManager.LoadScene(0);
}
}
}
I've also commented out some bits which set a max jump limit because they don't work so if anyone could help with that it would be great!
Answer by hexagonius · Jul 03, 2017 at 07:34 AM
Don't do MovePosition on a non kinematic rigidbody and don't use a separate AddForce. The best way to do this is to combine your movement into a single vector and assign that to the rb.velocity. But most of all, do either of any of the ways you do it in FixedUpdate. That's where Physics Updates need to be performed.
Thanks for that! Any tips on how to set a jump height limit though?
Your answer
Follow this Question
Related Questions
2D 360 degress platformer example needed 0 Answers
How can I add an impulse force on top of my walking force? 1 Answer
Quake Movement in Unity 1 Answer
How Time.deltaTime affects movement ? 4 Answers
My player's movement is slippery 1 Answer