Chetan Waghela
Chetan Waghela

Reputation: 137

Start C# script when image is detected for Vuforia+Unity

I have written a script, say like spiraling a sphere to the center in C#. However, the script starts even before the image target is detected and when I place the image target in front of camera the script is already executed.

I read that the DefaultTrackableBehaviour script needs to be modified for this. I saw some videos which show how to start audio when the image target is detected, however how do I start a script when the image target is detected.

This is the hierarchy of the objects enter image description here

This is the script I want to execute for the sphere only when the image target is detected. On execution the sphere will spiral to the center (0,0,0)

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

public class spiralanti : MonoBehaviour
{
    float angles;
    float radiuss;
    float angleSpeed;
    float rSpeed;
    // Start is called before the first frame update
    void Start()
    {
        angles = 0;
        radiuss = 1f;
        angleSpeed = 250f;
        rSpeed = 0.05f;
        angles = Mathf.Max(0, Mathf.PI);
        radiuss = Mathf.Max(0, radiuss);

        //float x = 0;
        // float y = 0;
        // float z = 0;
    }

    // Update is called once per frame
    void Update()
    {
        angles += Time.deltaTime * angleSpeed;
        radiuss -= Time.deltaTime * rSpeed;
        if (radiuss <= 0)
        {
            float x = 0;
            float y = 1;
            float z = 0;

            transform.localPosition = new Vector3(x, y, z);
        }

        else
        {
            float x = radiuss * Mathf.Cos(Mathf.Deg2Rad * angles);
            float z = radiuss * Mathf.Sin(Mathf.Deg2Rad * angles);
            float y = 1;

            transform.localPosition = new Vector3(x, y, z);
        }


        }

 }

Please help.

Upvotes: 1

Views: 2378

Answers (1)

Divyansh Gupta
Divyansh Gupta

Reputation: 311

  1. In DefaultTrackableBehaviour script, make a bool variable targetFound.
  2. Copy everything from your script's Start() method and add to DefaultTrackableBehaviour script's start() method.
  3. Copy and add Update() method from your script to DefaultTrackableBehaviour script
  4. Add an if condition in Update() method to check if targetFound is true or false, execute Update() code on if targetFound is true.
  5. Set targetFound value to be true in onTrackingFound() method.
public bool targetFound = false;
void onTrackingFound() {
          targetFound = true;
        }
void Update() {
         if (targetFound){
          // your code here
       }
}

Upvotes: 1

Related Questions