- Home /
Trigger collision detection problem
I have a thin box that has an image of text on it that in landscape is two screen height high. I want the user to be able to scroll this text up and down freely to read the text.
I have a box off screen at the top and bottom in position to stop the text box going too far in either direction that have colliders set as triggers.
The text box is set with a rigid body.
The trigger code for each barrier box is as follows:
public class TopTriggerController : MonoBehaviour {
public static bool canScrollUp = true;
void OnTriggerEnter (Collider other) {
if (other.gameObject.name == "textCube") {
canScrollUp = false;
}
}
void OnTriggerExit (Collider other) {
canScrollUp = true;
}
}
public class BottomTriggerController : MonoBehaviour {
public static bool canScrollDown = true;
void OnTriggerEnter (Collider other) {
if (other.gameObject.name == "textCube") {
canScrollDown = false;
}
}
void OnTriggerExit (Collider other) {
canScrollDown = true;
}
}
Which makes sense to be in that if the text box moves up or down too far these triggers will set the flag accordingly to prevent further movement in that direction.
However I think the code in my update method may be at fault as although I do get a collision and the scroll stops it only does so once from the start in either direction. So I scroll up and it stops correctly I scroll down a bit then scroll back up and the trigger no longer fires?
Here is my update code that I am trying to get the text to scroll up and down as the users drags their finger up and down where dragSpeed is set to 3.0f
void Update () {
if (Input.touchCount > 0) {
// grab reference to this touch
Touch userTouch = Input.GetTouch (0);
// ray from cameara to point of finger touch
Ray ray = Camera.main.ScreenPointToRay (userTouch.position);
// hit object to record details of what was hit (touched)
RaycastHit hit;
// if we got a hit and it was on one of the buttons
if (Physics.Raycast (ray, out hit) && (hit.collider.gameObject.name == "textCube")) {
if (userTouch.phase == TouchPhase.Began) {
lastY = userTouch.position.y;
}
if (userTouch.phase == TouchPhase.Moved) {
if (lastY < userTouch.deltaPosition.y && TopTriggerController.canScrollUp){
transform.Translate(new Vector3(transform.position.x,transform.position.y, -dragSpeed) * Time.deltaTime);
}
if (lastY > userTouch.deltaPosition.y && BottomTriggerController.canScrollDown) {
transform.Translate(new Vector3(transform.position.x,transform.position.y, dragSpeed) * Time.deltaTime);
}
lastY = userTouch.position.y;
}
}
}
}
Am I making a silly schoolboy error?
Thanks in advance
Your answer
![](https://koobas.hobune.stream/wayback/20220613172240im_/https://answers.unity.com/themes/thub/images/avi.jpg)