- Home /
Touch different Gameobjects using camera array and raycast hit
I want to be able to touch a cube in the scene and have it print "cube" in the debug log and when I touch a sphere in the same scene I want it to print "sphere". This is what i have...
function Update () {
for (var touch : Touch in Input.touches){
var ray = Camera.main.ScreenPointToRay(touch.position);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
print("cube");
// this piece of code enables me to touch both cube and sphere but only display
//"cube" in the debug log...
// I dont know how to separate the two
}
}
}
}
Answer by Seth-Bergman · Nov 13, 2012 at 09:55 PM
you're not using a Debug.Log (at least not shown here).. You're using "print"
you have a line that says
print("cube");
(not technically a Debug.Log)
this prints the word "cube" no matter what gets hit, the cube, the sphere, etc..
you could replace that line with this:
print("Hit: " + hit.collider.name);
for a Debug Log, it would say:
Debug.Log("Hit: " + hit.collider.name);
(to answer your other question, you can access the tag the same way, from the hit.collider):
...etc
if (Physics.Raycast (ray, hit, 100)) {
if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
if(hit.collider.tag == "someTag") {
...etc
Thanks so much man! I really appreciate it. Ive been on this issue for like 5 hrs now. I feel dumb on how simple that was... i was using GameObject.FindWithTag("cube"), but didn't work.. Anyway. Thanks again.
Answer by PlanetTimmy · Nov 13, 2012 at 10:03 PM
Use the collider member of the RaycastHit variable you pass through to Raycast:
var ray = Camera.main.ScreenPointToRay(touch.position); var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
print(hit.collider.name);
}
}
In this case it's printing out the name of the object which has the collider component on, but you could check the tag or layer or anything else you like to work out what it is you've hit.
Answer by test84 · Nov 13, 2012 at 09:18 PM
Why don't you tag each of them and then in the ray cast section, check tag of the object.
i have the game objects tagged but im not sure where to check for the tags... in what section of my code do i need to check for them?
how can i use this code, to the touch just work on the 3D SPHERE, and not the whole screen. any help...thanks
Your answer
Follow this Question
Related Questions
GameObject Moving Slow when drag with hand 0 Answers
Camera collision detection. 0 Answers
Help destroying gameObject on RayCastHit? 1 Answer
checking colliders from multiple raycast 1 Answer
Orthographic Camera Raycast using ScreenPointToRay 2 Answers