- Home /
Raycast from touch, return if hit a specific object.
I've been working at this code for a little bit now, I need to get it so that when the user taps the screen it sends a ray from his touch position, if this ray hits "greenbox" then it continues beyond the "if" statement. Here's what I have so far, the problem is under the "tapgreen" function
#pragma strict
var bestscore;
var score : float;
var levelchose : int;
var levelmultiplier : int;
var timerscript : Timer;
var greenbox : GameObject;
var greenboxcollide : Collider;
var scorecounter : Transform;
timerscript = gameObject.GetComponent("Timer");
function Start () {
Startgame();
levelmultiplier = 1;
}
function Update () {
// Do a ready, set, go function
}
function Startgame () {
levelchose = Random.Range(1, 1);
if (levelchose == 1)
{
Tapgreen();
}
Debug.Log("Didn't flip");
}
function Challengecomplete () {
timerscript.Timerstop();
score = score + timerscript.finaltime*levelmultiplier;
levelmultiplier = levelmultiplier+1;
Instantiate (scorecounter, Vector2(0.0, 0.0), Quaternion.identity);
}
function OnGUI()
{
GUI.Box(new Rect(100, 10, 50, 20), "" + score.ToString("0"));
}
function Tapgreen () {
// Player must tap the green square.
Debug.Log("Ready");
yield WaitForSeconds (2);
Debug.Log("Set");
yield WaitForSeconds (2);
Debug.Log("GO!");
timerscript.Timerstart();
Instantiate (greenbox, Vector2(Random.Range(-2.68, 2.68), Random.Range(-4.5, 4.5)), Quaternion.identity);
for (var touch : Touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
// Construct a raycast from the coordinates of the touch
var ray = Camera.main.ScreenPointToRay (touch.position);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit)) {
if (hit.collider == greenbox.collider)
{
// If ray collides
Destroy (greenbox);
Challengecomplete();
}
}
}
}
}
function Slider () {
//Player must slide slider all the way to the right
}
function Gameover () {
Debug.Log("Gameover function called");
score = score + timerscript.timer*levelmultiplier;
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613151751im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Character keeps snapping between two finger positions [Mobile, Android, Raycast] 0 Answers
Shooting works with PC Keyboard, but not Mobile Touch Controls?! 1 Answer
how to move an object in 4 directions by tilting device when not parallel to the ground 0 Answers
How can i call the 'col' object from the Update function? 1 Answer
Internal collisions 1 Answer