- Home /
The question is answered, right answer was accepted
Issues with jump control for player
I created a movement script for a player (cube). The movement seems to working fine but the jump control seems to be messed up.
What I wanted : To make the cube jump once until it collides with a surface.
Whats I got : The cube jumps once when I press the jump key (space) and when I hit the space key multiple times the cube does a double jump.
I would also like to know if there is any better way to write a movement script.
Thank you in advance.
Code :
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ball_movement : MonoBehaviour {
public float speed;
public float jumpforce;
private bool isground;
Rigidbody rb;
Vector3 jump;
void Start()
{
isground = true;
rb = GetComponent<Rigidbody> ();
jump = new Vector3 (0f, jumpforce, 0f);
}
void OnCollisionStay(Collision other)
{
if(other.gameObject.CompareTag("Ground"))
isground = true;
}
void Update()
{
float movex = Input.GetAxis("Horizontal");
float movey = Input.GetAxis("Vertical");
this.transform.Translate (movex * speed * Time.deltaTime, 0f, movey * speed * Time.deltaTime);
if(Input.GetKeyDown(KeyCode.Space) && isground)
{
rb.AddForce (jump*jumpforce, ForceMode.Impulse);
//rb.velocity = jump;
isground = false;
}
}
}
Answer by Thaun_ · Nov 30, 2017 at 10:49 AM
It is probably cause the isGround is setting to true just after you jump. What you could do is to check if your Y Velocity is 0.
if(GetComponent<Rigidbody>().velocity.y <= 0){
isground = true;
}else{
isground = false;
}
(On Update) or just simply,
isground = GetComponent<Rigidbody>().velocity.y <= 0;
Follow this Question
Related Questions
How to make an enemy ragdoll on death? 1 Answer
Changing scenes without a new script? 1 Answer
Adding animation from other model on character 0 Answers
Must I attach every script to a gameobject in order to work ? 2 Answers
Can I make Money collecting script without attaching it to a object ? I tried but I got error 2 Answers