- Home /
Fix flying control
Hi guys, my intention was to create a character (a bird) that flies; so I added a Jump control script, a constant force that pulls him down, and I've set him as rigidbody (for collisions with objects). So I should press Jump button to balance the bird in the air (when he goes too high or on the groud he dies). The code works but: when I press the jump button more than 2 times, he flies too high and the constant force isn't high enough to push him down or ,if I set constant force higher, he falls faster down. Here is the code for the Jump Button:
public class Jump : MonoBehaviour {
bool JumpPressed=false;
public float jumpAccelleration=3;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (!JumpPressed)
JumpPressed = Input.GetKeyDown (KeyCode.Space);
}
void FixedUpdate(){
if (JumpPressed) rigidbody.AddForce (new Vector3 (0, jumpAccelleration,0), ForceMode.Impulse);
if (JumpPressed) JumpPressed = false;
}
}
Can someone improve my code or give me some tips to control better my character??
PS. Sorry for bad english, I'm italian :D
You need a variable in there to deter$$anonymous$$e if AddForce should be allowed to happen, based on vertical velocity, such as if(rigidbody.velocity.y < maxJumpSpeed) then allow the AddForce().
Answer by gogott · Jan 27, 2014 at 01:24 AM
Instead of 2 " if (JumpPressed) " You can do it with:
if (JumpPressed)
{
rigidbody.AddForce (new Vector3 (0, jumpAccelleration,0), ForceMode.Impulse);
JumpPressed = false;
}
Play with the rigidbody properties. It all depends on what's the mass and the drag of it. You most likely have it very light, so you can either increase it's mass or decrease the jumpAccelleration.
Thank you very much for help :D I played with mass and drag and I obtained a nice balance. Now I've to optimize it with animations. Anyway I don't realize why I wrote 2 "if" code for the same thing ^^