Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by EdJampo · Jun 24, 2016 at 04:59 AM · 2d2d-platformer

How can I make my "Squat" button register with just a press?

While testing out some of the things I've learnt so far in Unity, I've just encountered a problem I don't understand. In the following script, I intend to make my 2D Player Character perform a squat animation once I press the "Space" key on my keyboard. He is expected to squat only when isSquatting is false and idle when the "Space" button is pressed and isSquatting is true. But this only happens very randomly while I press the key multiple times. I would be grateful if any knowledge to make my script better is shared.

using UnityEngine; using System.Collections; using UnityStandardAssets;

public class Player_Walk : MonoBehaviour {

 // Variables used by the function "flipDirection"
 private enum FaceDirection { FACINGLEFT = -1, FACINGRIGHT = 1};
 FaceDirection fd = FaceDirection.FACINGRIGHT;
 Vector3 localScale_temp = new Vector3();

 // Variablies used by various functions
 private Rigidbody2D thisRigidbody2D = null;
 private Transform thisTransform = null;


 // Variables used by the function "Walk"
 string walk_axis = "Horizontal";
 float walk_axis_val = 0f;
 public float walk_speed = 500f;
 Vector3 velocity_temp = new Vector3();
 Animator walk_animator;

 // Variables used by the function "Squat"
 bool isSquatting = false;
 string squat_button = "Jump";

 void Awake () {
     thisRigidbody2D = GetComponent<Rigidbody2D>();
     thisTransform = GetComponent<Transform>();
     walk_animator = GetComponent<Animator>();
 }
 
 // Update is called once per frame
 void Update () {
     Walk();
     Squat();
 }

 void Walk()
 {
     if (isSquatting)
     {
         walk_animator.SetBool("startSquat", false);
     }
     walk_axis_val = UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetAxis(walk_axis);
     thisRigidbody2D.AddForce(Vector2.right * walk_speed * walk_axis_val * Time.deltaTime);
     if (walk_axis_val != 0f)
     {
         walk_animator.SetBool("startWalk", true);
     }
     else{
         walk_animator.SetBool("startWalk", false);
     }
     Debug.Log("Velocity is " + thisRigidbody2D.velocity.ToString());

     velocity_temp = thisRigidbody2D.velocity; 
     velocity_temp.x  = Mathf.Clamp(velocity_temp.x, -10, 10);
     thisRigidbody2D.velocity = velocity_temp;

     if ((walk_axis_val < 0 && fd != FaceDirection.FACINGLEFT) || (walk_axis_val > 0 && fd != FaceDirection.FACINGRIGHT)){
         flipDirection();
         fd = (FaceDirection)((int)(fd) * -1);
     }
 }

 void flipDirection() {
     localScale_temp = thisTransform.localScale;
     localScale_temp.x *= -1;
     thisTransform.localScale = localScale_temp;
 }

 void Squat()
 {
     if (UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetButtonDown(squat_button) && !isSquatting)
     {
         walk_animator.SetBool("startSquat", true);
         isSquatting = true;
     }

     else if (UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetButtonDown(squat_button) && isSquatting)
     {
         walk_animator.SetBool("startSquat", false);
         isSquatting = false;
     }
     
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Endless_Aftermath · Jun 24, 2016 at 09:21 AM

In your Squat() method you have a serious looping issue that keeps cancelling itself out. You're trying to give too much direction. I'll walk you through the corridors of your own code.

You only want this guy to squat when the button is pressed, right? So make that happen.

Your code as it is: When Squat() runs and you are holding down the space button at first, isSquatting is false and then it is set to true and you get what you want..squatting.

      if(UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetButtonDown(squat_button) && !isSquatting)
      {
          walk_animator.SetBool("startSquat", true);
          isSquatting = true;
      }

But then Squat() runs around on the next Update() call, you are still holding the space key, and isSquatting is true.. What do you think will occur? It skips past the first if statement because it no longer holds true and runs the "else if" piece.

  (UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetButtonDown(squat_button) && isSquatting)
      {
          walk_animator.SetBool("startSquat", false);
          isSquatting = false;
      }

So, basically by doing things this way, you are making the character squat and not squat continuously. You are also doing this in your Walk() function, which I can imagine, between both of these loopings of on and off, looks very wonky, to say the least. This hurts your characters legs with all these muscle spasms. Let's look at a different way. If we are holding in the button, we want to be squatting else, he's not squatting.

 void Update()
 {
   if(Input.GetKey(KeyCode.Space))
   {
     Squat();
   }
   else
   {
      Walk();
   }
 }

And your other code for your Walk() and Squat() functions get simplified too...

  void Walk()
  {
    walk_animator.SetBool("startSquat", false);
     isSquatting = false;
 
      walk_axis_val = UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager.GetAxis(walk_axis);
      thisRigidbody2D.AddForce(Vector2.right * walk_speed * walk_axis_val * Time.deltaTime);
      if (walk_axis_val != 0f)
      {
          walk_animator.SetBool("startWalk", true);
      }
      Debug.Log("Velocity is " + thisRigidbody2D.velocity.ToString());
      velocity_temp = thisRigidbody2D.velocity; 
      velocity_temp.x  = Mathf.Clamp(velocity_temp.x, -10, 10);
      thisRigidbody2D.velocity = velocity_temp;
      if ((walk_axis_val < 0 && fd != FaceDirection.FACINGLEFT) || (walk_axis_val > 0 && fd != FaceDirection.FACINGRIGHT)){
          flipDirection();
          fd = (FaceDirection)((int)(fd) * -1);
      }
  }
 
  void Squat()
  {
          walk_animator.SetBool("startWalk", false);
          walk_animator.SetBool("startSquat", true);
          isSquatting = true;
  }


Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image EdJampo · Jun 24, 2016 at 11:04 AM 0
Share

Thank you very much. It worked.

avatar image Endless_Aftermath EdJampo · Jun 24, 2016 at 02:21 PM 0
Share

You are very welcome. Glad it worked for you. I could have just given you the code, but I wanted to make sure you saw what was going on for future reference in your coding adventures. Good luck n your project!

avatar image EdJampo Endless_Aftermath · Jun 24, 2016 at 06:58 PM 0
Share

Yeah, I now completely understand what is going on in my code because of your explanation. Thank you!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

2D Platform Player moving instantly from upper platform to lower, only when moving left 0 Answers

Scale object, collision not working 2 Answers

,Hey! I'm trying to make a Dash move like Celeste but my Dash doesn't seem to work Horizontally(X Axis), My Dash is working perfectly fine Upward and Downwards(Y Axis). 1 Answer

Level design clone of King of Thieves 0 Answers

OnTriggerEnter2D Running twice when destroying game object. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges