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 Clevereen · Jun 12, 2018 at 06:32 PM · velocityboolontriggerenter2d

How to force a value stored in variable?

Hello,

i've looking for hours how to force a bool variable from "true" to "false". I'm using 2 scripts and what i want to do is :

  • When the player enters a zone he can climb

  • When the player press "jump", he cannot climb anymore, even if he's still in the Zone

why it doesn't work?

     /*WHEN PLAYER USE A LIANA TO CLIMB, THE CHARACTER GOES TO THE EDGE OF COLLIDER*/
     void OnTriggerEnter2D(Collider2D collision)
     {
         //FROM THE COLLIDED GameObject
         Transform[] arrayCollidedGO = collision.GetComponentsInChildren<Transform>(true);//get the children of the collided object
 
         for(int i = 0; i < arrayCollidedGO.Length; i++)
         {
             if (arrayCollidedGO[i].gameObject.CompareTag("climbLayer"))//if the tag name of the collided object is "liana"
             {
                 print("FROM canClimb : enterdetect");
                 canGetClimb = true;
                 motor.AllowClimbing(canGetClimb);
             }
         }
 
     }

Then the 2nd script with the condition:

                 if (velocity.y!=0)//velocity.y>0 Allow to jump on liana
                 {
                     rb.constraints &= ~RigidbodyConstraints2D.FreezePositionX;//| unfreeze position
                     canClimb = false;
                     rb.gravityScale = 2;
                     print("FROM playerMotorV3.cs : jumpFromLiana");
                     rb.AddForce(new Vector2(velocity.x, velocity.y) * jumpSpeedLiana * Time.deltaTime, ForceMode2D.Impulse);//permet de sauter
                 }


even if i Jump, the bool stays "true", it doesn't change oO

Comment
Add comment · Show 1
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 bakir-omarov · Jun 12, 2018 at 07:05 PM 0
Share

motor.AllowClimbing(canGetClimb); what is it? Is it somehow connected with second script?

It is hard to say something with just this parts of scripts, upload whole script. I think it is because you are colliding with trigger while jump, so every frame you are trying to make canClimb true/false from 2 different scripts/functions. So for sure i need to see whole scripts.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Clevereen · Jun 12, 2018 at 07:30 PM

hello,

thank you for your answer! here some pictures to explain what i'm trying to do: 1-the first triggered zone is very big (enter zone) to avoid (i think) to collide again. It sets canClimb to 1 2- the second is another triggered zone to align the hand with the edge collider 3- if the hand AND can climb is true, then he can climb

alt text

alt text

FROM canClimb.cs using System.Collections; using System.Collections.Generic; using UnityEngine;

 public class canClimb : MonoBehaviour
 {
     private playerMotorV3 motor;//Call the class playerMotorV2
     //CANCLIMB
     private bool canGetClimb;
     private Transform[] parentGo;
     public int numRef;
 
     // Use this for initialization
     void Start()
     {
         canGetClimb = false;
         parentGo = GetComponentsInParent<Transform>(true);//get all the gO of Parent including Child Use this for initialization
         for (int i = 0; i < parentGo.Length; i++)
         {
             if (parentGo[i].transform.CompareTag("playerFloween"))
             {
                 numRef = i;//to store the value of the parentgO playerFloween
                 print("From lianaTriggered : the number of gO playerFloween is : " + numRef);
             }
         }
 
         //GIVE INFORMATION TO PLAYER MOTOR
         motor = parentGo[numRef].GetComponent<playerMotorV3>();    //recupérer un composant sur l'objet
     }
 
     // Update is called once per frame
     void Update()
     {
 
     }
 
     /*WHEN PLAYER USE A LIANA TO CLIMB, THE CHARACTER GOES TO THE EDGE OF COLLIDER*/
     void OnTriggerEnter2D(Collider2D collision)
     {
         //FROM THE COLLIDED GameObject
         Transform[] arrayCollidedGO = collision.GetComponentsInChildren<Transform>(true);//get the children of the collided object
 
         for(int i = 0; i < arrayCollidedGO.Length; i++)
         {
             if (arrayCollidedGO[i].gameObject.CompareTag("climbLayer"))//if the tag name of the collided object is "liana"
             {
                 print("FROM canClimb : enterdetect");
                 canGetClimb = true;
                 motor.AllowClimbing(canGetClimb);
             }
         }
 
     }

FROM PLAYER MOTOR using System.Collections; using System.Collections.Generic; using UnityEngine; using Spine.Unity;

//[RequireComponent(typeof(playerController))] //lorsque ce script est attaché à un objet, celui-ci sera rattaché automatiqu

public class playerMotorV3 : MonoBehaviour {

 private Vector2 velocity;//variable local
 private Rigidbody2D rb;
 private Transform[] parentPlayer;
 [SerializeField] //permet de la modifier dans l'éditeur
 private float maxSpeed,maxSpeedJump,radiusCircleFeet;
 [SerializeField] private GameObject groundCheck;
 [SerializeField] private LayerMask layer;

 //DECLARATION FOR LIANA
 private Vector2 up;//local variable
 [SerializeField] private float jumpSpeedLiana,upSpeed,radiusCircleHand;
 [SerializeField] private GameObject lianaCheck;
 [SerializeField] private LayerMask lianaLayer;

 //CANCLIMB
 public bool canClimb;

 //VARIABLE DECLARATION
 public float angle;
 public Vector2 normalVector;
 private float characterAngle;//to store the value of the current character Angle
 private SkeletonAnimation skeletonAnimation;

 // Use this for initialization
 void Start ()
 {
     velocity = Vector2.zero;
     rb = GetComponent<Rigidbody2D>();
     skeletonAnimation = GetComponent<SkeletonAnimation>();
     parentPlayer = GetComponentsInParent<Transform>(true);
 }
 
 // Update is called once per frame
 //Pour gérer la physique on a besoin d'un fixeUpdate
 void FixedUpdate ()
 {
     PerformRunAndJump();//on appel la fonction PerformRunAndJump     
                         //Vector2 ray = transform.TransformDirection(Vector2.down) * 4;//create a raycast in the down direction
                         //Debug.DrawRay(transform.position, Vector2.down, Color.red);
     
 }
 
 public void AllowClimbing(bool getCanClimb) //this methods is called by lianaTriggered
 {
     canClimb = getCanClimb;//information from lianaTriggered
 }

 public void RunAndJumpUp(Vector2 _velocity,Vector2 getGoUp) //this methods is called in playerMotors
 {
     velocity = _velocity;
     up = getGoUp;


     if (velocity.y > 0)
     {
         skeletonAnimation.loop = false;
         skeletonAnimation.AnimationName = "jump_2";
         skeletonAnimation.timeScale = 1;//change the speed of animation to 100%

     }
     if(velocity.y>0 && velocity.x < 0)
     {
         skeletonAnimation.loop = false;
         skeletonAnimation.AnimationName = "jump_2";
         
     }
     if(velocity.y>0 && velocity.x>0)
     {
         skeletonAnimation.loop = false;
         skeletonAnimation.AnimationName = "jump_2";
         
     }
     else
     {
         skeletonAnimation.loop = true;
         
     }

 }



 private void PerformRunAndJump()
 {
     bool liananed = Physics2D.OverlapCircle(lianaCheck.transform.position, radiusCircleHand, lianaLayer);
     bool grounded = Physics2D.OverlapCircle(groundCheck.transform.position, radiusCircleFeet, layer);//va creer un cercle.Si ce cercle rencontre un layer=1 sinon 0



     

     //CONDITION FOR GROUND
     if (grounded)//allow to jump if grounded
     {

         //print("ground" + rotationZ);
         rb.constraints &= ~RigidbodyConstraints2D.FreezePositionX;//unfreeze
         //rb.freezeRotation = true; //to freeze rotation on Z value
         //ALLOW TO JUMP
         rb.AddForce(new Vector2(0f, velocity.y) * maxSpeedJump * Time.deltaTime, ForceMode2D.Impulse);//permet de sauter



     }

     //CONDITION FOR LIANA

     
     if (liananed)//allow to climb if liana contact
     {

             rb.bodyType = RigidbodyType2D.Dynamic;
             rb.velocity = new Vector2(0f, up.y * upSpeed * Time.deltaTime);//climb

         if (canClimb)
         {
             rb.gravityScale = 0;//to set no gravity if the player touch the liana

             // print("FROM playerMotorV3 : " + parentPlayer[1]);
             
             

             if (up.y > 0)
             {
                 print("FROM playerMotor V3 : climb");
                 skeletonAnimation.loop = true;
                 skeletonAnimation.timeScale = 1;//change the speed of animation to 100%
             }
             else if (up.y == 0)
             {
                 skeletonAnimation.loop = true;
                 skeletonAnimation.timeScale = 0;//change the speed of animation to 0%
             }
             if (up.y < 0)
             {
                 print("FROM playerMotor V3 : climb");
                 skeletonAnimation.loop = true;
                 skeletonAnimation.timeScale = 1;//change the speed of animation to 100%
             }

             if(velocity.y>0)
             {
                 rb.constraints &= ~RigidbodyConstraints2D.FreezePositionX;//| unfreeze position
                 canClimb = false;
                 print("FROM playerMotorV3.cs : "+canClimb);
                 rb.gravityScale = 2;
                 print("FROM playerMotorV3.cs : jumpFromLiana");
                 rb.AddForce(new Vector2(velocity.x, velocity.y) * jumpSpeedLiana * Time.deltaTime, ForceMode2D.Impulse);//permet de sauter
             }

             
         }
           



     }
     
     else
     {
         rb.gravityScale = 2;
     }

     


     //RUN
     rb.velocity = new Vector2(velocity.x * maxSpeed * Time.deltaTime, rb.velocity.y); //permet d'avancer =>quand on va tomber, lors de l'appui sur


         if (velocity.x > 0 && grounded && velocity.y == 0)
         {
             characterAngle = 0;
             skeletonAnimation.AnimationName = "Run"; //change the name of the skeletonanimation
             skeletonAnimation.timeScale = 1;//change the speed of animation to 100%
             skeletonAnimation.loop = true;
         }
         if (velocity.x < 0 && grounded && velocity.y == 0) //When the character runs to the opposite way
         {
             characterAngle = 180;
             skeletonAnimation.AnimationName = "Run";
             skeletonAnimation.timeScale = 1;
             skeletonAnimation.loop = true;

         }
         else if (velocity.x == 0 && grounded)
         {
             skeletonAnimation.AnimationName = "idle";
             skeletonAnimation.loop = true;
             skeletonAnimation.timeScale = 1;
         }


     //RAYCAST TO ANALYSE
     RaycastHit2D footAngleHit = Physics2D.Raycast(transform.position - new Vector3(0, 5f), Vector2.up, 5f, layer);//the start point is the transform position. Because the start point is the middle of the character, we remove 1.7 on y axis to start the raycast on the edge of the feet
     Debug.DrawRay(transform.position - new Vector3(0, 5f), (Vector2.up) * 5f, Color.red);//The original raycast to analyse
     Debug.DrawRay(transform.position - new Vector3(0, 1.75f), -footAngleHit.normal * 3f, Color.blue);//normal raycast angle of collided ground

     //TO LIMIT THE Z ROTATION
     if (footAngleHit.collider != null)
     {
         Transform objectHit = footAngleHit.transform;//to get the name of the collided gO
                                                      //print("Touch the ground : " + objectHit.name);
         normalVector = -footAngleHit.normal; //Get the normal value
         angle = Vector2.Angle(Vector2.down, normalVector) + 180;

         if (normalVector.x < 0 || normalVector.y < 0) //si x ou y inférieur à 0
         {
             angle = -angle;
         }

         //print("==FROM playerMotorV2== angle between vector2 down and footAngleHit : " + angle);
        // transform.rotation = Quaternion.Euler(-180, 0, angle);

     }
     else
     {
        // transform.rotation = Quaternion.Euler(0, 0, 0);
         angle = 0;
     }

     //APPLY THE FLIP ANGLE TO THE CHARACTER
    transform.rotation = Quaternion.Euler(0,characterAngle, angle);
  
 }

 private void OnDrawGizmos()
 {
     Gizmos.color = Color.red;//rightFoot
     Gizmos.DrawSphere(groundCheck.transform.position, radiusCircleFeet);
     Gizmos.color = Color.red;//righttHand
     Gizmos.DrawSphere(lianaCheck.transform.position, radiusCircleHand);

 }

}

when i press jump, i can see in the log that canJump switch to "false" than when i reale the space key it goes back immediatly to "TRUE".

I'm sure it has something to do with passing the variable, public variable...


trigg2.jpg (23.4 kB)
trigge1.jpg (62.3 kB)
Comment
Add comment · 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
0

Answer by bakir-omarov · Jun 12, 2018 at 07:59 PM

I think when you are pressing Jump, your velocity is greater than 0, so you Unity will execute this code:


    if(velocity.y>0)
              {
                  rb.constraints &= ~RigidbodyConstraints2D.FreezePositionX;//| unfreeze position
                  canClimb = false;
                  print("FROM playerMotorV3.cs : "+canClimb);
                  rb.gravityScale = 2;
                  print("FROM playerMotorV3.cs : jumpFromLiana");
                  rb.AddForce(new Vector2(velocity.x, velocity.y) * jumpSpeedLiana * Time.deltaTime, ForceMode2D.Impulse);//permet de sauter
              }


Good, but after it, you don't change your canClimb back to true never. You have to exit your current trigger, and enter it back for triggering it, and then you will change your canClimb from OnTriggerEnter.

I think you can add some new bool to your playerMotorV3 script, like private bool m_jumping;.
And then make it true if velocity.y>0 , and make false if it is not. And before you can climb you have to check two bools canClimb and !m_jumping (m_jumping == false). So you will check if i can climb (it is meaning that you are on trigger zone) and if i am not jumping.


P.S this can be wrong, because i am sleepy and tired today:/

P.S #2... You can cut it short and try to add grounded to your this line:


    if (canClimb && grounded) // HERE // HERE// HERE // HERE // HERE
         {
             rb.gravityScale = 0;//to set no gravity if the player touch the liana
                                 // print("FROM playerMotorV3 : " + parentPlayer[1]);


So you will check if you are grounded and canClimb , then only allow to climb. And you have to remove canClimb = false; from if(velocity.y>0).

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 Clevereen · Jun 12, 2018 at 08:12 PM 0
Share

hello,

thank you.

that's why i did that. Because i don't want to set canClimb to true, UNLESS i re-enter the triggered zone. But when i jump it switch correctly to "False" then back immediatly to "True" without reason!

when i jump, i want the bool canClimb to falsd.

avatar image bakir-omarov Clevereen · Jun 12, 2018 at 08:23 PM 0
Share

There may be only 2 ways:

1) Your trigger is working several times, you can check it by looking your debu, if you will find here print("FRO$$anonymous$$ canClimb : enterdetect"); after jumping, that is it! Say me and we will kill/fix it.
2) You have another script that also sending you player$$anonymous$$otorV3.AllowClimbing(true);

avatar image Clevereen bakir-omarov · Jun 14, 2018 at 01:16 PM 0
Share

After hours of works, it finally works, but i don't know why…. I changed the name of my variable that has the same name of the class ...maybe it was that?

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

85 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to create a cooldown for my homingMissiles? 0 Answers

Velocity powered rigidbody on a moving platform without parenting. 3 Answers

Why is the relativeVelocity of a Collision always zero in OnCollisionEnter and OnCollisionStay? 0 Answers

[Solved] How to shoot an object in front of the player? 1 Answer

How do I accelerate particles in Shuriken? 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