- Home /
Applying an Initial force on button press, and a constant force while its held down that gets weaker over time?
I knew this wouldn't work, but wanted to try to model it as best I could to see if I could figure it out myself, but now I'm a bit stuck.
I am trying to model flying, when the space button is pressed, the character flaps, applying a force directly upwards. When the button is held down, I need a constant force to be applied, as if the character is gliding. I modeled this using drag, but of course that stops the force from the initial flap from working. When the player lets go of the button, it is meant to remove the drag (or force) and the character falls as normal. I was thinking I could either use a constant force, or delay when the drag is added until the player is at the height of their 'jump', but couldn't figure out how either work.
public Vector2 jumpForce = new Vector2(0, 300);
public int glideForce = 50;
private int currentGlideForce = 50;
private bool isGliding = false;
private int iGlide = 0;
void Update (){
// Jump
if (Input.GetKeyDown ("space")) {
if (isGliding == false){
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce (jumpForce);
currentGlideForce = glideForce;
iGlide = 0;
}
}
//Glide
if (Input.GetKey ("space")) {
rigidbody2D.drag = currentGlideForce;
//simulating gliding
if (currentGlideForce >= 0 ){
if (iGlide % 5 == 0){ //simple solution to make the drag reduce over time. Will implement a proper solution later
currentGlideForce--;
}
}
isGliding = true;
}
if (Input.GetKeyUp ("space")) {
isGliding = false;
rigidbody2D.drag = rigidbody2D.drag - currentGlideForce; //resets the drag to neutral
}
}
When I tried to model it using a constant force instead, the game just crashed, so I don't know if I was even close to getting it to work. This is the code I used for that
rigidbody2D.constantForce.force = currentJumpForce;
if (currentJumpForce.x >= 0) {
if (iGlide % 5 == 0) {
currentJumpForce.Set(currentJumpForce.x - 5,0);
}
isGliding = true;
Your answer
Follow this Question
Related Questions
Simultaneous Touch Drag Controls 0 Answers
Implementing snake-like 2D controls and behavior 1 Answer
Remove Drag/Friction 1 Answer
How to check force or velocity on character? 1 Answer
2d rigidbody drag on x, y axis 0 Answers