Hi, I’m a beginner and I’m trying to do a simple autojump, but I got some glitches.
Here is the glitch: it jumps some times lot more than it should, sometimes lot less, and always at different altitude.
Here is my script: (ofc I have all “using…”)
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public float JumpForce;
private Rigidbody rig;
void Awake()
{
// get the components
rig = GetComponent<Rigidbody>();
}
void Update()
{
move();
if (Input.GetKey("space"))
{
tryJump();
}
//else if (Input.GetButtonDown("Jump"))
// tryJump();
}
void tryJump()
{
Ray ray1 = new Ray(transform.position + new Vector3 (0.50f,0,0.5f), Vector3.down);
Ray ray2 = new Ray(transform.position + new Vector3(0.5f, 0, -0.5f), Vector3.down);
Ray ray3 = new Ray(transform.position + new Vector3(-0.5f, 0, 0.5f), Vector3.down);
Ray ray4 = new Ray(transform.position + new Vector3(-0.5f, 0, -0.5f), Vector3.down);
bool cast1 = Physics.Raycast(ray1, 0.50f);
bool cast2 = Physics.Raycast(ray2, 0.50f);
bool cast3 = Physics.Raycast(ray3, 0.50f);
bool cast4 = Physics.Raycast(ray4, 0.50f);
if (cast1 || cast2 || cast3 || cast4)
rig.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
}
void move ()
{
float xIN = Input.GetAxis("Horizontal");
float zIN = Input.GetAxis("Vertical");
Vector3 dir = new Vector3(xIN, 0, zIN) * moveSpeed;
dir.y = rig.velocity.y;
rig.velocity = dir;
}
I don’t really know if this is the best way for jump, but it should still work I guess.
So, why if I use Input.GetButtonDown(“Jump”) it’s ok? What do I have to add in the code? Thank you!