- Home /
button as gameobject child
Hi!!!
I have being hitting my head with a problem and I'm in desperate need of help...
I need to use 3d objects inside a GameObject as buttons (go to game, go to x place... etc...) For an Android system (So, based on touch)
When I finally made the system check the collision between my finger and the damn button... all four buttons do what one of them is doing... I'll explain... if I have 4 buttons that go to different application.LoadLevel... It does not matter which one I press... al go to the same one.
Code as follows.
function Update ()
{
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
var ray = Camera.main.ScreenPointToRay (touch.position);
if (Physics.Raycast (ray))
{
Application.LoadLevel("introduccion");
}
}
}
}
Code works... But all 4 buttons have different programming ( Application.LoadLevel("Different Level") ) and the other 3 buttons redirect to "introduccion" anyway.
Those 4 scripts are attached to the childs of a GameObject (that can be a problem, I Know, but I have no choice (Using Metaio Mobile SDK and need to place al the AR 3D objects that are going to be shown in a single gameObject)
Thanks!
Answer by moichezmoi · Mar 27, 2012 at 08:07 PM
Hi,
The problem, here, is that Physics.Raycast(ray) will return true if the ray detects any collider, from any gameobject, and not only the collider of the gameobject the script is attached to.
To check the collider, you need to change your code as followed :
if (touch.phase == TouchPhase.Began)
{
var ray = Camera.main.ScreenPointToRay (touch.position);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
//here, we check if the detected collider is the one attached to the gameobject
if (hit.collider == collider)
Application.LoadLevel("introduccion");
}
Now, I'm not sure about the syntax because I'm not used to javascript, but the exemple given at the very bottom of this page is quite similar.
Answer by janoman · Apr 26, 2012 at 06:45 PM
Hi!
Thanks, that was indeed the error... I could not make it to the right javascript syntax... So I did implement a not to elegant solution, but it works...
This is it.
function Update ()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray.origin, ray.direction, hit))
{
if (Input.GetMouseButtonDown(0))
{
if(hit.collider.tag == ("btnup"))
{
Application.LoadLevel("introduccion");
}
if(hit.collider.tag == ("btnleft"))
{
Application.LoadLevel("cata");
}
if(hit.collider.tag == ("btnright"))
{
Application.LoadLevel("maridaje");
}
if(hit.collider.tag == ("btnbottom"))
{
Application.OpenURL ("http://www.x.com/");
}
}
}
}
Thanks again, and sorry for the delay in answering, but my work has me swarmed :S
Good luck!
Your answer
