简体   繁体   中英

Unity: How to create an on land event c#

I wanto play squeeze animation for my character whenever it lands on ground. I have the animation and ground check. I want to set a bool that remains true for a second whenever i land on the ground from air. When I use invoke method in update, it changes the value of bool every frame. Can someone help me. The code looks something like this:

void Update()
{
    if (isGrounded)
    { 
     justLanded = true;
     Invoke("justLandedExit", 3f);
    }
}
void justLandedExit()
{
  justLanded = false;
}

If you make isGrounded a property you can have it trigger a delegate and it would look something like this

Such as:

public Action<bool> OnGroundedChanged;

private bool _isgrounded; // your base value dont just set this unless you dont want to call the OnGroundedChanged!

private bool IsGrounded
{
  get { return _isgrounded; }
  set {
         if (value!=_isgrounded) // eg has changed  avoids dup calls
         {
           _isgrounded=value;
           if (OnGroundedChanged != null) OnGroundedChanged(_isgrounded);
         }
       }
}
      

   

then somnewhere in your code like the OnCollission just call IsGrounded=true, and it will do the rest

You can have a bool called wasLanded that works in fixed update like that:

void Update()
{
   isGrounded = DetectGround();

   if(isGrounded && !wasGrounded)
   {
      PlayAnimation();
   }
}

void LateUpdate()
{
   wasGrounded = isGrounded;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM