Home > database >  How do I Spawn random rewards by clicking on Bushes in my 2D game?
How do I Spawn random rewards by clicking on Bushes in my 2D game?

Time:07-24

In my 2D game i have a scene where when the user clicks on the Bushes random Herbs will spawn i don't know if the Idea of spawning random Herbs is going to be correct for the thing i want to use. but this is the picture from my game:

Picture of bushes from the game

My idea is to put 3 spawn points behind those bushes so they can randomize the herbs i have after clicking on the bushes.

Then i have the script which is this one:

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

public class HerbSpawner : MonoBehaviour
{
    //Here, we declare variables.
    public GameObject objToSpawn;
    //public means the var is exposed in the inspector, which is super helpful.
    public float timeLeft, originalTime;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //tick down our timer:
        timeLeft -= Time.deltaTime;
        //timeLeft = timeLeft - Time.deltaTime;
        if (timeLeft <= 0)
        {
            SpawnIt();

            //reset the time:
            timeLeft = originalTime;
        }

        //let's also spawn on button press:
        if (Input.GetButtonDown("Jump"))
        {
            SpawnIt();
        }
    }

    void SpawnIt()
    {
        //spawn our coin:
        Instantiate(objToSpawn, transform.position, Quaternion.identity);
    }
}

CodePudding user response:

Ok, I get it, you want to click on the bushes to spawn herbs. For that, add a box collider to the bushes and set the tag of the bush gameobject to "Bush". Now in the Update() method, add the following code

if (Input.GetMouseButtonDown(0)) {
    RaycastHit2D hit = Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition));

    if (hit.collider && hit.collider.CompareTag("Bush")) {
        SpawnIt();
    } 
}
  • Related