- Home /
This question was
closed Oct 09, 2015 at 09:56 PM by
Ashky for the following reason:
The question is answered, right answer was accepted
Question by
Ashky · Oct 03, 2015 at 11:54 AM ·
raycasttouchraycasthittouchphase
Casting a ray at touch position
Hello Unity Community!
I am trying to cast a ray in depth, to check if an object was tapped or not. I'm using this code here:
private void CheckTap(){
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began){
Vector3 a = new Vector3(Input.GetTouch(0).deltaPosition.x,Input.GetTouch(0).deltaPosition.y,-1.0f);
RaycastHit h;
if(Physics.Raycast(a,Vector3.forward,out h,10.0f,lmask)){
Debug.Log(a);
if(h.transform.gameObject.tag=="Square") {
h.transform.gameObject.GetComponent<script_SquareHub>().OnHit();
}
}
}
}
However, the ray is cast only at (0,0,-1), all the time. Why is this happening, why is my ray origin always at 0,0,-1 ? This particular code works fine if the object is around x,y~0.
Thanks for your time!
Comment
Best Answer
Answer by fffMalzbier · Oct 03, 2015 at 12:50 PM
The first example of thedocumentation page is not what you are searching for , use the third one
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public GameObject particle;
void Update() {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// Construct a ray from the current touch coordinates
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
// Create a particle if hit
if (Physics.Raycast(ray))
Instantiate(particle, transform.position, transform.rotation);
}
}
}
}
If you like to have the Touch position you have to use Input.GetTouch(i).position instad of Input.GetTouch(i).deltaPosition
Yes, this works perfectly. Sorry, I got caught up in coding and forgot to reply and accept answer.