- Home /
Question by
W_bushell · Feb 17, 2017 at 09:14 AM ·
2d-platformerrigidbody2dboxcollider2d
How do i make my grounded variable change as I hit the platform and as I jump?
The Trigger entry and exits arent working and the boolean stays as false
using System.Collections; using UnityEngine;
public class CarMovement : MonoBehaviour { public float speed; public bool grounded = false; public float reverse;
void Update () {
if (Input.GetKey (KeyCode.RightArrow)) {
if (grounded = true) {
float moveHorizontal = Input.GetAxis ("Horizontal");
Vector2 movement = new Vector2 (moveHorizontal, 0.0f);
GetComponent<Rigidbody2D> ().AddForce (movement * speed);
}
else if (grounded = false)
{
}
}
if (Input.GetKey (KeyCode.LeftArrow)) {
if (grounded = true) {
float moveHorizontal = Input.GetAxis ("Horizontal");
Vector2 movement = new Vector2 (moveHorizontal, 0.0f);
GetComponent<Rigidbody2D> ().AddForce (movement * reverse);
}
}
}
void OnTriggerEntry2D () {
grounded = true;
}
void OnTriggerExit2D () {
grounded = false;
}
}
Comment
Answer by Paddog · Feb 17, 2017 at 10:27 AM
If you want to use the in Unity build Colliders the correct Function is https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
void OnTriggerEnter2D(Collider2D col){
grounded = true;
}
and make sure your colliders are set to trigger.
Answer by jwulf · Feb 17, 2017 at 10:19 AM
It is OnTriggerEnter2D (not OnTriggerEnt ry 2D).
See https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612111154im_/https://answers.unity.com/themes/thub/images/avi.jpg)