- Home /
Touch input not working
I am trying to create a button using a sprite with a box collider 2D attached. I have got it to work without using raycast but it is not very accurate. Now it does not do anything when I press the button.
I have used the documentation to put this together.
var levelToLoad : String;
var newSprite : Sprite;
function Update ()
{
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// Construct a ray from the current touch coordinates
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
if (Physics.Raycast (ray)) {
GetComponent(SpriteRenderer).sprite = newSprite;
LoadNewLevel();
Debug.Log("Touched");
}
}
}
}
function LoadNewLevel()
{
yield WaitForSeconds(0.5);
Application.LoadLevel(levelToLoad);
}
Thanks.
Answer by Jamie_h88 · May 12, 2014 at 01:01 PM
In the end I had trouble with both answers. Tested and Working now, it was much simpler than I was making it.
Here is the code that will allow a button to change sprite and load the level you want:
var levelToLoad : String;
var newSprite : Sprite;
function Update ()
{
var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);
if(Input.touchCount > 0)
{
if(hit.collider.name == "Button")
{
GetComponent(SpriteRenderer).sprite = newSprite;
LoadNewLevel();
}
}
}
function LoadNewLevel()
{
yield WaitForSeconds(0.5);
Application.LoadLevel(levelToLoad);
}
Answer by HarshadK · May 12, 2014 at 11:39 AM
In your Physics.Raycast you need to specify the distance for the ray.
Refer: Physics.Raycast
So your if loop becomes
if (Physics.Raycast (ray, 100)) {
DoSomeStuff();
}
Also if you want to detect the collider which the ray hit you can use:
var hit : RaycastHit;
if(Physics.Raycast(ray, hit, 100)) {
print(hit.collider.name);
}
Thought I had this sorted but it still does not seem to work. I have tried using physics2D but it is still not detecting the touch.
Answer by Ashish Dwivedi · May 12, 2014 at 11:52 AM
You are using 2D collider that's why you have to use "Physics2D.Raycast()". I hope this would help you...
Your answer
Follow this Question
Related Questions
android touch optimization issue 1 Answer
Prevent Raycast on reacting to GUI input? 2 Answers
Why Raycast is not working properly? 0 Answers
Confused as to how my RaycastHit script works 1 Answer
Getting material index from raycast 2 Answers