how can i use a for loop so my character can double jump?












0















I am trying to code a platforming game as right now all my character model can do is either jump infinitely or doesn't jump at all. I want to use a for loop so my character can jump one when grounded and once more when he is in the air but I cant figure out how to make it stop after double jumping once and resetting when the character hits the floor again. please help!!



public class SimplePlatformController : MonoBehaviour
{

[HideInInspector]
public bool facingRight = true;
[HideInInspector]
public bool jump = false;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;




private bool grounded = false;
private Animator anim;
private Rigidbody2D rb2d;


// Use this for initialization
void Awake()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
for (int i = 0; i <= 1; i++)
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

if (Input.GetButtonDown("Jump") && grounded)
{
i = 0;
jump = true;

}

if (Input.GetButtonDown("Jump") && !grounded)
{
jump = true;
i = i + 1;
}

}
}

void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");

anim.SetFloat("Speed", Mathf.Abs(h));

if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);

if (Mathf.Abs(rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);

if (h > 0 && !facingRight)
Flip();
else if (h < 0 && facingRight)
Flip();

if (jump)
{
anim.SetTrigger("Jump");
rb2d.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}


void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

}









share|improve this question

























  • For Loop --Adding for reference

    – Symon
    Nov 21 '18 at 16:10













  • Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

    – Ryan Wilson
    Nov 21 '18 at 16:11











  • @RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

    – Sam Austin
    Nov 21 '18 at 16:17






  • 1





    @SamAustin can you explain why you want to use a for loop for this?

    – Eddge
    Nov 21 '18 at 16:18






  • 1





    @SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

    – Eddge
    Nov 21 '18 at 16:30


















0















I am trying to code a platforming game as right now all my character model can do is either jump infinitely or doesn't jump at all. I want to use a for loop so my character can jump one when grounded and once more when he is in the air but I cant figure out how to make it stop after double jumping once and resetting when the character hits the floor again. please help!!



public class SimplePlatformController : MonoBehaviour
{

[HideInInspector]
public bool facingRight = true;
[HideInInspector]
public bool jump = false;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;




private bool grounded = false;
private Animator anim;
private Rigidbody2D rb2d;


// Use this for initialization
void Awake()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
for (int i = 0; i <= 1; i++)
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

if (Input.GetButtonDown("Jump") && grounded)
{
i = 0;
jump = true;

}

if (Input.GetButtonDown("Jump") && !grounded)
{
jump = true;
i = i + 1;
}

}
}

void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");

anim.SetFloat("Speed", Mathf.Abs(h));

if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);

if (Mathf.Abs(rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);

if (h > 0 && !facingRight)
Flip();
else if (h < 0 && facingRight)
Flip();

if (jump)
{
anim.SetTrigger("Jump");
rb2d.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}


void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

}









share|improve this question

























  • For Loop --Adding for reference

    – Symon
    Nov 21 '18 at 16:10













  • Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

    – Ryan Wilson
    Nov 21 '18 at 16:11











  • @RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

    – Sam Austin
    Nov 21 '18 at 16:17






  • 1





    @SamAustin can you explain why you want to use a for loop for this?

    – Eddge
    Nov 21 '18 at 16:18






  • 1





    @SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

    – Eddge
    Nov 21 '18 at 16:30
















0












0








0


1






I am trying to code a platforming game as right now all my character model can do is either jump infinitely or doesn't jump at all. I want to use a for loop so my character can jump one when grounded and once more when he is in the air but I cant figure out how to make it stop after double jumping once and resetting when the character hits the floor again. please help!!



public class SimplePlatformController : MonoBehaviour
{

[HideInInspector]
public bool facingRight = true;
[HideInInspector]
public bool jump = false;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;




private bool grounded = false;
private Animator anim;
private Rigidbody2D rb2d;


// Use this for initialization
void Awake()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
for (int i = 0; i <= 1; i++)
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

if (Input.GetButtonDown("Jump") && grounded)
{
i = 0;
jump = true;

}

if (Input.GetButtonDown("Jump") && !grounded)
{
jump = true;
i = i + 1;
}

}
}

void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");

anim.SetFloat("Speed", Mathf.Abs(h));

if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);

if (Mathf.Abs(rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);

if (h > 0 && !facingRight)
Flip();
else if (h < 0 && facingRight)
Flip();

if (jump)
{
anim.SetTrigger("Jump");
rb2d.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}


void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

}









share|improve this question
















I am trying to code a platforming game as right now all my character model can do is either jump infinitely or doesn't jump at all. I want to use a for loop so my character can jump one when grounded and once more when he is in the air but I cant figure out how to make it stop after double jumping once and resetting when the character hits the floor again. please help!!



public class SimplePlatformController : MonoBehaviour
{

[HideInInspector]
public bool facingRight = true;
[HideInInspector]
public bool jump = false;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;




private bool grounded = false;
private Animator anim;
private Rigidbody2D rb2d;


// Use this for initialization
void Awake()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
for (int i = 0; i <= 1; i++)
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

if (Input.GetButtonDown("Jump") && grounded)
{
i = 0;
jump = true;

}

if (Input.GetButtonDown("Jump") && !grounded)
{
jump = true;
i = i + 1;
}

}
}

void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");

anim.SetFloat("Speed", Mathf.Abs(h));

if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);

if (Mathf.Abs(rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);

if (h > 0 && !facingRight)
Flip();
else if (h < 0 && facingRight)
Flip();

if (jump)
{
anim.SetTrigger("Jump");
rb2d.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}


void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

}






c# unity3d






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 16:52









Ruzihm

3,66111627




3,66111627










asked Nov 21 '18 at 16:08









Sam AustinSam Austin

11




11













  • For Loop --Adding for reference

    – Symon
    Nov 21 '18 at 16:10













  • Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

    – Ryan Wilson
    Nov 21 '18 at 16:11











  • @RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

    – Sam Austin
    Nov 21 '18 at 16:17






  • 1





    @SamAustin can you explain why you want to use a for loop for this?

    – Eddge
    Nov 21 '18 at 16:18






  • 1





    @SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

    – Eddge
    Nov 21 '18 at 16:30





















  • For Loop --Adding for reference

    – Symon
    Nov 21 '18 at 16:10













  • Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

    – Ryan Wilson
    Nov 21 '18 at 16:11











  • @RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

    – Sam Austin
    Nov 21 '18 at 16:17






  • 1





    @SamAustin can you explain why you want to use a for loop for this?

    – Eddge
    Nov 21 '18 at 16:18






  • 1





    @SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

    – Eddge
    Nov 21 '18 at 16:30



















For Loop --Adding for reference

– Symon
Nov 21 '18 at 16:10







For Loop --Adding for reference

– Symon
Nov 21 '18 at 16:10















Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

– Ryan Wilson
Nov 21 '18 at 16:11





Can't you add an event handler to the Input? Then when the jump button is hit you can do your logic inside the event handler

– Ryan Wilson
Nov 21 '18 at 16:11













@RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

– Sam Austin
Nov 21 '18 at 16:17





@RyanWilson im unsure how to set up an event handler sorry. (kinda new to all this coding stuff)

– Sam Austin
Nov 21 '18 at 16:17




1




1





@SamAustin can you explain why you want to use a for loop for this?

– Eddge
Nov 21 '18 at 16:18





@SamAustin can you explain why you want to use a for loop for this?

– Eddge
Nov 21 '18 at 16:18




1




1





@SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

– Eddge
Nov 21 '18 at 16:30







@SamAustin first, do your input detection inside of update, otherwise you will have issues with the FixUpdate loop on movement(such as movement appearing delay). Second you do not need a for loop for this, update runs every frame.

– Eddge
Nov 21 '18 at 16:30














1 Answer
1






active

oldest

votes


















1














A for loop is inappropriate for this, because you only want to advance the counter if you jump. and you need to leave the loop when it's time for the frame to end. You could in theory make it happen with a while loop in a Coroutine but that is unnecessarily complicated.



A better alternative is to just keep a counter as a class field and update it appropriately, according to the double jump state.



Also, since the if statement is being reached on every frame, you have to check if you have any more air jumps before you double jump.



If you want to be able to double-jump after you simply walk off a platform, you'll want to set the jump counter to 0 anytime grounded is set to be true.



Combining all of these suggestions might look like this:



public class SimplePlatformController : MonoBehaviour
{

// ...

private int airJumpCount = 0; // Add this counter

// ...

// Update is called once per frame
void Update()
{
grounded = Physics2D.Linecast(
transform.position, groundCheck.position,
1 << LayerMask.NameToLayer("Ground"));

if (grounded) airJumpCount = 0; // reset the counter when grounded

if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}

// Only enter the air jump block if we still have more air jumps
if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1)
{
airJumpCount++;
jump = true;
}
}

// ...
}





share|improve this answer





















  • 1





    What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

    – trollingchar
    Nov 21 '18 at 17:03











  • Good catch! I was editing the answer to handle that while you were writing that comment ;)

    – Ruzihm
    Nov 21 '18 at 17:12













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416111%2fhow-can-i-use-a-for-loop-so-my-character-can-double-jump%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














A for loop is inappropriate for this, because you only want to advance the counter if you jump. and you need to leave the loop when it's time for the frame to end. You could in theory make it happen with a while loop in a Coroutine but that is unnecessarily complicated.



A better alternative is to just keep a counter as a class field and update it appropriately, according to the double jump state.



Also, since the if statement is being reached on every frame, you have to check if you have any more air jumps before you double jump.



If you want to be able to double-jump after you simply walk off a platform, you'll want to set the jump counter to 0 anytime grounded is set to be true.



Combining all of these suggestions might look like this:



public class SimplePlatformController : MonoBehaviour
{

// ...

private int airJumpCount = 0; // Add this counter

// ...

// Update is called once per frame
void Update()
{
grounded = Physics2D.Linecast(
transform.position, groundCheck.position,
1 << LayerMask.NameToLayer("Ground"));

if (grounded) airJumpCount = 0; // reset the counter when grounded

if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}

// Only enter the air jump block if we still have more air jumps
if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1)
{
airJumpCount++;
jump = true;
}
}

// ...
}





share|improve this answer





















  • 1





    What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

    – trollingchar
    Nov 21 '18 at 17:03











  • Good catch! I was editing the answer to handle that while you were writing that comment ;)

    – Ruzihm
    Nov 21 '18 at 17:12


















1














A for loop is inappropriate for this, because you only want to advance the counter if you jump. and you need to leave the loop when it's time for the frame to end. You could in theory make it happen with a while loop in a Coroutine but that is unnecessarily complicated.



A better alternative is to just keep a counter as a class field and update it appropriately, according to the double jump state.



Also, since the if statement is being reached on every frame, you have to check if you have any more air jumps before you double jump.



If you want to be able to double-jump after you simply walk off a platform, you'll want to set the jump counter to 0 anytime grounded is set to be true.



Combining all of these suggestions might look like this:



public class SimplePlatformController : MonoBehaviour
{

// ...

private int airJumpCount = 0; // Add this counter

// ...

// Update is called once per frame
void Update()
{
grounded = Physics2D.Linecast(
transform.position, groundCheck.position,
1 << LayerMask.NameToLayer("Ground"));

if (grounded) airJumpCount = 0; // reset the counter when grounded

if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}

// Only enter the air jump block if we still have more air jumps
if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1)
{
airJumpCount++;
jump = true;
}
}

// ...
}





share|improve this answer





















  • 1





    What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

    – trollingchar
    Nov 21 '18 at 17:03











  • Good catch! I was editing the answer to handle that while you were writing that comment ;)

    – Ruzihm
    Nov 21 '18 at 17:12
















1












1








1







A for loop is inappropriate for this, because you only want to advance the counter if you jump. and you need to leave the loop when it's time for the frame to end. You could in theory make it happen with a while loop in a Coroutine but that is unnecessarily complicated.



A better alternative is to just keep a counter as a class field and update it appropriately, according to the double jump state.



Also, since the if statement is being reached on every frame, you have to check if you have any more air jumps before you double jump.



If you want to be able to double-jump after you simply walk off a platform, you'll want to set the jump counter to 0 anytime grounded is set to be true.



Combining all of these suggestions might look like this:



public class SimplePlatformController : MonoBehaviour
{

// ...

private int airJumpCount = 0; // Add this counter

// ...

// Update is called once per frame
void Update()
{
grounded = Physics2D.Linecast(
transform.position, groundCheck.position,
1 << LayerMask.NameToLayer("Ground"));

if (grounded) airJumpCount = 0; // reset the counter when grounded

if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}

// Only enter the air jump block if we still have more air jumps
if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1)
{
airJumpCount++;
jump = true;
}
}

// ...
}





share|improve this answer















A for loop is inappropriate for this, because you only want to advance the counter if you jump. and you need to leave the loop when it's time for the frame to end. You could in theory make it happen with a while loop in a Coroutine but that is unnecessarily complicated.



A better alternative is to just keep a counter as a class field and update it appropriately, according to the double jump state.



Also, since the if statement is being reached on every frame, you have to check if you have any more air jumps before you double jump.



If you want to be able to double-jump after you simply walk off a platform, you'll want to set the jump counter to 0 anytime grounded is set to be true.



Combining all of these suggestions might look like this:



public class SimplePlatformController : MonoBehaviour
{

// ...

private int airJumpCount = 0; // Add this counter

// ...

// Update is called once per frame
void Update()
{
grounded = Physics2D.Linecast(
transform.position, groundCheck.position,
1 << LayerMask.NameToLayer("Ground"));

if (grounded) airJumpCount = 0; // reset the counter when grounded

if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}

// Only enter the air jump block if we still have more air jumps
if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1)
{
airJumpCount++;
jump = true;
}
}

// ...
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 17:10

























answered Nov 21 '18 at 17:00









RuzihmRuzihm

3,66111627




3,66111627








  • 1





    What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

    – trollingchar
    Nov 21 '18 at 17:03











  • Good catch! I was editing the answer to handle that while you were writing that comment ;)

    – Ruzihm
    Nov 21 '18 at 17:12
















  • 1





    What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

    – trollingchar
    Nov 21 '18 at 17:03











  • Good catch! I was editing the answer to handle that while you were writing that comment ;)

    – Ruzihm
    Nov 21 '18 at 17:12










1




1





What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

– trollingchar
Nov 21 '18 at 17:03





What happens if he walks off a cliff without jumping? I think he will be unable to air-jump because airJumpCount was not reset

– trollingchar
Nov 21 '18 at 17:03













Good catch! I was editing the answer to handle that while you were writing that comment ;)

– Ruzihm
Nov 21 '18 at 17:12







Good catch! I was editing the answer to handle that while you were writing that comment ;)

– Ruzihm
Nov 21 '18 at 17:12




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416111%2fhow-can-i-use-a-for-loop-so-my-character-can-double-jump%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin