- Home /
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
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.
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
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...
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).
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.
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);
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
![](https://koobas.hobune.stream/wayback/20220612164628im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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