- Home /
onTouchEvent -like happenings in Unity3D
I'm trying to achieve something like onTouch event in Unity3D.
Basically what I want to do is trigger an event whenever a particular object is touched.
I tried using Input.touches but it also listens to touch events outside the object. How can I achieve this?
Answer by Fattie · Aug 23, 2012 at 09:17 AM
I'll tell you !
buy an iPad because it's happier than the google system :-)
you get the user's touch of their grubby finger on the glass. say it is at "355,234" just for example.
you RAYCAST from that point "355,234" in to the scene through the camera!
the RAYCAST might hit something. if so, which object is it? often it will just the ground, clouds, fat tourists standing around on beach, whatever
is your Particular Object touched? you're done!
Hope it helps!
There is a massive amount of advanced code on the topic here http://answers.unity3d.com/questions/292333/how-to-calculate-swipe-speed-on-ios.html
Note that, somewhat confusingly, you can either do this basically "on the object itself" (using collider.Raycast) or anywhere else (using Physics.Raycast)
Here's a general example
function Update()
{
// hello world example starter code for the consumer "touching"
// the object to which this script is attached.
for ( t = 0; t < Input.touches.Length; ++t )
if ( Input.touches[t].phase == TouchPhase.Began )
{
if ( collider.Raycast(
theCam.ScreenPointToRay(
Input.touches[t].position),
theHit,
83 )
)
_IGotTouched!!!();
}
}
private var theCam:Camera;
private var theHit : RaycastHit;
function Awake()
{
theCam = GameObject.Find("gameCam").GetComponent(Camera);
}
so it did appear.. haha :)) shame on me for such a lame question.. hehe, anyway, I did see somewhere the use of raycast but not really sure what it really is for, thanks for the clarification sir!)
I believe there is a component/object in Unity3D named RayCastHit, right? so I just have to use it and attach it to the object I want to be touched, am I getting this correct sir?
e.g., I want a sphere object to be able to receive touch events, I'd add a RayCastHit component there..
thanks :)
ok all you have to do is put the code given, in a script and attach that script to the sphere.
that script would be called a "component". you would be attaching it to the game object in question.
try it out, it will work perfectly!
You actually have to "do" a raycast. In fact the line of code "collider.Raycast..." is literally casting a ray for you.
Cheers
Your answer
