- Home /
UI rect touch is not working?
I create a new project
I create a canvas
I create a panel
I change the panel rect transform in the inspector to stretch
So, it looks like image 1.
Then I add this code to the UI panel.
private bool checkFirstTouch = true;
void OnEnable()
{
checkFirstTouch = true;
}
void Update () {
if (checkFirstTouch) {
if (Input.GetMouseButton (0)) {
foreach (Touch touch in Input.touches) {
if (gameObject.GetComponent<RectTransform>().rect.Contains(touch.position)) {
print ("Touched.");
checkFirstTouch = false;
}
}
}
}
}
My problem here is, that when I touch the screen on my mobile device, it's only working when I touch the left bottom corner. Please look image 2.
Why?
Why the whole screen is not working? Because the panel is stretched?
Must I multiply it with canvas scaler or what?
My canvas looks like this:
[Canvas]: Screen Space Overlay
[CanvasScaler]:
UI Scale Mode: Scale with Screen Size
Reference Resolution: X: 800, Y: 480
Screen Match Mode: Match Width Or Height
Match: 0.5
I'm using Unity 4.7.0.
EDIT:
If I print "gameObject.GetComponent ().rect", I get this:
(x:-400.00, y:-240.00, width:800.00, height:480.00)
Answer by valyard · Feb 15, 2016 at 03:24 PM
Well, you answered yourself (8
You have a (x:-400.00, y:-240.00, width:800.00, height:480.00) rect and you are trying to test a point which is inside a screen rect (x:0, y:0, width:800.00, height:480.00).
These 2 rects intersect exactly where you drew green rectangle on image 2.
I think you need either change your code togameObject.GetComponent<RectTransform>().rect.Contains(touch.position - new Vector2(Screen.width/2, Screen.height/2))
or move pivot on your panel so it would be in the corner.
Of course you also want to cache gameObject.GetComponent<RectTransform>()
and new Vector2(Screen.width/2, Screen.height/2)
in a variable.
It's a good help, but it's not working. I must check now, where the problem is.
It's now like this:
Your answer
Follow this Question
Related Questions
Unity 2D GameObject Movement.(C#) 0 Answers
Rect to RectTransform on overlay Canvas? 1 Answer
GetComponent() Problem with getting value. 1 Answer
Canvas shrinks over time 0 Answers
Is it possible to change Rect Transform Scale throw script 1 Answer