Log in or register to post comments

how at add touch listener to 3D object in unity

April 26, 2012 - 5:59am #1

Hello,
Im trying to make the 3 D objects that are placed on the imagetarget to act like a button.Say you touch that 3D object , and it calls a browser or it calls another scene/an activity..

How can i achieve this ..
Thank you
Mukundan

how at add touch listener to 3D object in unity

April 26, 2018 - 2:11am #31

I am also new to Unity and am wanting to do the same.  I need to have several touchable objects that trigger by touch/tap on a larger 3D model.

I am confused on exactly where to attach the raycaster script, though.  Do we attach it to the ARcamera? That's the only camera I have in the scene and it doesn't have a child.

how at add touch listener to 3D object in unity

March 25, 2018 - 8:42pm #30

Hi elixirbash

 

I am new to Vuforia and want to implement a feature where I want to add touch feature to Augmented 3D image and show some information in screen may be in canvas form, but really have no idea how to implement it. Your problem seemed like you where performing something similar to it. Can you please guide me thorough the same. I am able to Augment a 3D image but how to add touch feature and how to display information in screen I have no idea about it. 

how at add touch listener to 3D object in unity

June 8, 2017 - 8:38pm #29

Hello, Thnks for great info. There's only one thing that I want to ask, if I click on the 3D object, then, a canvas will appear.

Its just then, when I click the button to close it, Its not working. What should I do with this exit button. I already put :

public void hideCanvas()

{

  textCanvas.enabled = false;

  outButton.enabled = true;

}

how at add touch listener to 3D object in unity

March 20, 2017 - 3:11am #28

ptachaneu, I am not able to see any message when i click on the 3d model, I have added the script to my 3d model which has a collider and i've also added the physics raycaster to my camera i.e a child to ARcamera... where am i doing wrong? please help

how at add touch listener to 3D object in unity

March 3, 2017 - 6:37am #27

I attached a script to make a text box appear, but now it appears as soon as I switch to the game mode.

I also tried to use ".SetActive(false)" in the same script but it does not work.

How can I tell the box to stay inactive until I touched/clicked on the part of the 3D model/collider?

Thank you, I 'll appreaciate your replies!

how at add touch listener to 3D object in unity

March 1, 2017 - 1:26pm #26

This works! Thank you!

The message appears showing that I clicked on the part of 3D object. Would it be the same if I touch the object within the app?

And how can I make a text field appear while clicking on this object? Also using a script, right?

how at add touch listener to 3D object in unity

February 28, 2017 - 11:21pm #25

In Hierarchy the actual camera object is inside ArCamera (child), so select it and you should see a camera component on it in the inspector window, press "Add Component" button and type "Physics Raycaster" and click to add it.

how at add touch listener to 3D object in unity

February 28, 2017 - 12:33pm #24

Thank you, misher, great! Since I am new here, I ask stupid questions, sorry. So I attach this script to the part of my 3D object where I use collider.

Then I attach a Raycasting script to my AR Camera?

 

:

how at add touch listener to 3D object in unity

February 28, 2017 - 4:33am #23

Here is a simple and tested component script that you can use on any 3d (or even UI) object in order to detect Single or Double Tap gestures (You will see in inspector 2 events). For 3d object there must be a collider, also make sure there is Physics Raycaster component attached to the Camera, if not - add one.

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class TapsEvents : MonoBehaviour, IPointerDownHandler {

    // You can add listeners in inspector
    public UnityEvent OnSingleTap;
    public UnityEvent OnDoubleTap;


    float firstTapTime = 0f;
    float timeBetweenTaps = 0.2f; // time between taps to be resolved in double tap
    bool doubleTapInitialized;

    public void OnPointerDown(PointerEventData eventData)
    {
        if (!doubleTapInitialized)
        {
            // invoke single tap after max time between taps
            Invoke("SingleTap", timeBetweenTaps);
            // init double tapping
            doubleTapInitialized = true;
            firstTapTime = Time.time;
        }
        else if (Time.time - firstTapTime < timeBetweenTaps)
        {
            // here we have tapped second time before "single tap" has been invoked
            CancelInvoke("SingleTap"); // cancel "single tap" invoking
            DoubleTap();
        }
    }

    void SingleTap()
    {
        doubleTapInitialized = false; // deinit double tap

        // fire OnSingleTap event for all eventual subscribers
        if(OnSingleTap != null)
        {
            OnSingleTap.Invoke();
        }
    }

    void DoubleTap()
    {
        doubleTapInitialized = false;
        if(OnDoubleTap != null)
        {
            OnDoubleTap.Invoke();
        }
    }
}

how at add touch listener to 3D object in unity

February 27, 2017 - 12:05pm #22

@elpuerco63, I would like to try the same:

By clicking on the 3D object or in the part of it (collider), I want a text field or a pop-up window appear. 

I am new to Unity and Scripting and have no idea of how to implement it. 

Could you please give an example or share your code if it is possible for you? 

I'll apreciate it! 

Thank you!

 

 

how at add touch listener to 3D object in unity

April 6, 2016 - 6:23am #21

I take a different approach.  I add colliders set as triggers on the augmented gameobjects I wish to interact with.  Then in my scene manager script or relavent script I perform the raycast and query the gameobjet name and act accordingly.

how at add touch listener to 3D object in unity

January 21, 2016 - 11:53pm #20

Hello all,

 

I have attached the below code to the AR Camera as to detect the different augmentations and drag them using touch input.

This piece of code works fine with default camera but with the AR Camera and touch input, this doesn't seem to work.

Also I have a specific doubt. The AR Camera prefab that comes with Vuforia has a child camera tagged by default as Main Camera.

So being a newbie to Unity and Vuforia, I am not able to figure out to which of these should i attach my codes. I have tried changing the layer of AR Camera, its child and the objects on the scene to a separate layer(eg layer 10). but it doesnt seem to work too

Hoping to receive some inputs.

using UnityEngine;
using Vuforia;
using System.Collections;
using System.IO;
using UnityEngine.UI;

public class trial : MonoBehaviour {
 
 private GameObject focusObj = null;
 private float focusx;
 private float focusy;
 private float focusz;


 void Update()
 { 

   if(Input.touchCount>0 && Input.GetTouch(0).phase==TouchPhase.Began)
   {
    focusObj = null;
    Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
    RaycastHit hit;
    
    if(Physics.Raycast(ray, out hit, Mathf.Infinity))
     
    {
     focusObj=hit.transform.gameObject;
    }
   }
   
   
   if(focusObj && Input.touchCount >0 && Input.GetTouch(0).phase == TouchPhase.Moved)
   {
    focusx= Input.GetTouch(0).deltaPosition.x/500;
    focusz= 0;
    focusy= Input.GetTouch(0).deltaPosition.y/500;
    
    Vector3 pos =  new Vector3(focusx, focusz, focusy);
    focusObj.transform.position += pos;
    
   
   }
   if(focusObj && Input.touchCount >0 && Input.GetTouch(0).phase == TouchPhase.Ended)
   {
    focusObj=null;
   }
 
 }
}

 

how at add touch listener to 3D object in unity

January 10, 2016 - 12:35pm #19

Hello everyone, 

 

I am also trying to recognize touches on objects (image targets, to be exact). I added an else statement to the code provided below, to check whether I hit anything when I click (in play mode) on the screen. It always tells me that I am not hitting anything (i.e., the casted ray does not collide anywhere). Do I have to add a collider component to the image target? I tried doing so (I added a mesh collider, since my image targest are meshes), and it still comes up with "you didnt hit anything". 

Am I missing something really obvious? Did I add the wrong collider?
 

Regards

coernel

 

edit: clarified that I'm using mesh colliders

how at add touch listener to 3D object in unity

August 18, 2015 - 6:40am #18

You Sir, saved my life

how at add touch listener to 3D object in unity

August 11, 2015 - 1:34am #17

 

void Update () {
		if (Input.GetMouseButtonDown(0)){ // if left button pressed...
			Ray ray =Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast(ray, out hit)){
				if(hit.collider.tag == "clickableCube")
				{
					GameObject obj=GameObject.FindGameObjectWithTag("clickableCube");
					obj.GetComponent<Animation>().Play("cube");
				}
			}
		}
	}

Simply attach this script to ARCamera and add a tag for your desired gameobject this was working fine for me

how at add touch listener to 3D object in unity

September 28, 2014 - 8:32am #16

elixirbash wrote:

Thank you DavidBeard for your prompt reply..Will try this out now.. Mukundan

How can i resolve this error? i drag the code to my game object and im getting this error. Help please,

NullReferenceException: Object reference not set to an instance of an object
ObjectHighlighter.Start () (at Assets/Qualcomm Augmented Reality/Scripts/ObjectHighlighter.cs:18)
 

how at add touch listener to 3D object in unity

September 28, 2014 - 8:31am #15

How can i resolve this error? i drag the code to my game object and im getting this error. Help please,

NullReferenceException: Object reference not set to an instance of an object
ObjectHighlighter.Start () (at Assets/Qualcomm Augmented Reality/Scripts/ObjectHighlighter.cs:18)
 
Thanks.

how at add touch listener to 3D object in unity

November 30, 2013 - 11:28am #14

Yes you'll need to use the name of your object in Find() - you can either add it as a string ( .Find("object_name") or define the variable using the object name. 

how at add touch listener to 3D object in unity

November 30, 2013 - 10:14am #13

Hello, anyone can help?

how at add touch listener to 3D object in unity

November 17, 2013 - 9:48am #12

First Script in ArCamera

Second Script in ImageTarget

in this code -> baseObject      = GameObject.Find( obj_name );

obj_name <- i must change this with my 3D object name?

right?

which part i must change if i want to show a text or pop up window?

how at add touch listener to 3D object in unity

July 23, 2013 - 1:21pm #11

NEWER UPDATE
I got this working on an android ASUS TF300T, but had to change a few things for Unity 4.1.5 and the device.

In the "onTouchDown" C# script that is assigned to the ARCamera I added a simple integer to use with the for loop "touchCorrection" to add to the "i" counter in the for loop.  I did this because the android tab would only trigger the button with 2 fingers (one touching and the 2nd tapping).

using UnityEngine;
using System.Collections;
using System.Collections.Generic;



public class OnTouchDown : MonoBehaviour {
	
	// Update is called once per frame
	void Update () {
		
		int touchCorrection = 1;
		
		RaycastHit hit = new RaycastHit();
        for (int i = 0; i+touchCorrection < Input.touchCount; ++i) {
            if (Input.GetTouch(i).phase.Equals(TouchPhase.Began)) {
            // Construct a ray from the current touch coordinates
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
            if (Physics.Raycast(ray, out hit)) {
                hit.transform.gameObject.SendMessage("OnMouseDown");
              }
	    }
	  }
	
	}
}

Next I updated the script example below by getting rid of the "+Base"; string concatonation in the obj_name value assignment.  It seems this must be because GetComponent no longer needs the "Base" string concatonated on the gameObject name. (not sure though).

using UnityEngine;
using System.Collections;

public class ObjectHighlighter : MonoBehaviour {
	
	bool isHighlighted = false;
	Material originalMaterial;
	Material redMaterial;
	MeshRenderer meshRenderer;
	
	GameObject baseObject;
	string obj_name;
	// Use this for initialization
	void Start () {
	
		obj_name 		= this.gameObject.name;
		baseObject 		= GameObject.Find( obj_name );
		meshRenderer 		= baseObject.GetComponent<MeshRenderer>();
		originalMaterial 	= meshRenderer.material;
		
		Color red 			= new Color(255.0f,0.0f,0.0f, 0.5f);
		redMaterial  		= new Material(Shader.Find("Transparent/Parallax Specular"));
		redMaterial.color 	= red;
		
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnMouseDown(){
		
		Debug.Log("OMD "+obj_name);
		isHighlighted = !isHighlighted;
		
		if( isHighlighted == true ){
			
			HighlightRed();
			
		}
		if ( isHighlighted==false ){
			
			RemoveHighlight();
		}
	}
	
	void HighlightRed(){
		
		meshRenderer.material = redMaterial;
		Debug.Log("IT SHOULD BE RED");
	}
	
	void RemoveHighlight(){
		
		meshRenderer.material = originalMaterial;
	}
}

 

how at add touch listener to 3D object in unity

September 9, 2012 - 11:42pm #10

elixirbash wrote:

My question here is since the actual button is placed over its shadow object, why is the shadow object getting detected but not the main object.. this is lil tricky here

Have a look at the box colliders. Maybe the box collider of the shadow object is overlapping the one of the other object, thus making it impossible for the raycast to hit it.

how at add touch listener to 3D object in unity

September 7, 2012 - 5:26pm #9

When I try to use this Raycasting approach with these snippets of code I crash (EXC_BAD_ACCESS), which isn't very useful, but I can see from the debugger that it can't get past:

meshRenderer = baseObject.GetComponent<MeshRenderer>();

 
The crash occurs after the app is fully loaded, the Vuforia plug-in has logged the number of trackables, the the number of virtual buttons... but before the scene is 100% loaded and active on the iPad it hangs.  There are MeshRenderer components on the objects I'm trying to use this on (I've tried a variety of objects).  Any thoughts on why I can't seem to get a pointer to the meshRenderer?
 
If I figure it out myself, I'll of course report back.  Thanks.

how at add touch listener to 3D object in unity

September 4, 2012 - 11:59am #8

Thanks for the script. Works nicely. Although initially I made a mistake of adding the code to existing script attached to ARCamera. The code must be in its own script file.

Re: how at add touch listener to 3D object in unity

April 27, 2012 - 9:06am #7

:p DavidBeard,
your script is so good.. it worked ..
i added
Debug.Log("Touch event is called "+ hit.transform.gameObject); in the script and found that it is detecting the "shadow button object" .i added the second script you had suggested to the "main button object" and not its shadow object.Hence the thingy dint work.

My question here is since the actual button is placed over its shadow object, why is the shadow object getting detected but not the main object.. this is lil tricky here

Thanks for your time and support

Thank you guys

Re: how at add touch listener to 3D object in unity

April 27, 2012 - 8:13am #6

avidBeard,
I think i missed something here

This is what i did
1)Added the first script to ar camera
2)added the second script to the 3D objects

Outcome:
Wherever i touch ,whether on the object or on the empty space only ARCamera game object is selected.I added this log statement to OnTouchDown.cs
if (Physics.Raycast(ray, out hit)) {
hit.transform.gameObject.SendMessage("OnMouseDown");
Debug.Log("Touch event is called"+ gameObject);
}

log file :

04-27 20:37:23.161: I/Unity(8699): Touch event is calledARCamera (UnityEngine.GameObject)
04-27 20:37:23.161: I/Unity(8699): UnityEngine.Debug:Internal_Log(Int32, String, Object)
04-27 20:37:23.161: I/Unity(8699): UnityEngine.Debug:Log(Object)
04-27 20:37:23.161: I/Unity(8699): OnTouchDown:Update()

I know im missing something silly here, please throw some light on this ...
Thank you

DavidBeard wrote:

Add the second script to the objects, not the camera. Only the first script goes on the ARCamera.

Re: how at add touch listener to 3D object in unity

April 27, 2012 - 7:23am #5

Add the second script to the objects, not the camera. Only the first script goes on the ARCamera.

Re: how at add touch listener to 3D object in unity

April 27, 2012 - 3:02am #4

@DavidBeard:
I added the first script to the ARCamera ,and built and run ..Whereever i touch on the screen only ARCamera is considered as the game object.. it is not considering the individual 3D objects at all..Should i include the imagetarget as a child to the ARCamera ?
The 3Dobjects are child of the imagetarget..
How do i handle this

Re: how at add touch listener to 3D object in unity

April 26, 2012 - 10:50pm #3

Thank you DavidBeard for your prompt reply..Will try this out now..

Mukundan

Re: how at add touch listener to 3D object in unity

April 26, 2012 - 7:51am #2

Here is an example. Attach this script to your ARCamera in the Hierarchy.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class OnTouchDown : MonoBehaviour
{
    void Update () {
       
        RaycastHit hit = new RaycastHit();
        for (int i = 0; i < Input.touchCount; ++i) {
            if (Input.GetTouch(i).phase.Equals(TouchPhase.Began)) {
            // Construct a ray from the current touch coordinates
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
            if (Physics.Raycast(ray, out hit)) {
                hit.transform.gameObject.SendMessage("OnMouseDown");
              }
           }
       }
    }
}

This will determine which object has been touched using RayCasting. In this example the script triggers an OnMouseDown event on the object, which you could handle as such..

using UnityEngine;
using System.Collections;

public class ObjectHighlighter : MonoBehaviour {
	
	bool isHighlighted = false;
	Material originalMaterial;
	Material redMaterial;
	MeshRenderer meshRenderer;
	
	GameObject baseObject;
	string obj_name;
	// Use this for initialization
	void Start () {
		
		obj_name 			= this.gameObject.name + "Base";
		baseObject 			= GameObject.Find( obj_name );
		meshRenderer 		= baseObject.GetComponent<MeshRenderer>();
		originalMaterial 	= meshRenderer.material;
		
		Color red 			= new Color(255.0f,0.0f,0.0f, 0.5f);
		redMaterial  		= new Material(Shader.Find("Transparent/Parallax Specular"));
		redMaterial.color 	= red;
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void OnMouseDown(){
		
		Debug.Log("OMD "+obj_name);
		isHighlighted = !isHighlighted;
		
		if( isHighlighted ){
			
			HighlightRed();
			
		}else{
			
			RemoveHighlight();
		}
	}
	
	void HighlightRed(){
		
		meshRenderer.material = redMaterial;
	}
	
	void RemoveHighlight(){
		
		meshRenderer.material = originalMaterial;
	}
}

This script can be attached to any GameObjects that you want to use as buttons. In this example, the object will be turned red, provided that it's using a Transparent/Parallax Specular shader.

Check out the Unity reference docs for the other features you need. The Application class can be used to accomplish what you're looking for.

Log in or register to post comments