WACK-A-MOLE QUEST: ‘Tricky Patterns’ - Solutions

Quest: Wack-A-Mole Quest
Challenge: Tricky Patterns

Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.

Using the animation editor, you can move the Body (not Enemy) to a third location. When you click the record button and slide the white line past the end of the animation and move the body, it will add that movement to the animation. I only moved mine at a right angle and made it pop up at the third location. You have to keep in mind that the box may end up out of the play field.

1 Like

this was a major headache for me and ended up taking about 3 hours. First I remade the animation (had to review how that stuff works together) so that all it does is pop the enemy up and then back down. Then I created a new EnemyMover class to deal with the hidden movement. I had some trouble with getting the animation to run properly but eventually got it working just the way I intended

using UnityEngine;

public class EnemyMover : MonoBehaviour
{
    [SerializeField] Animator animator;
    [SerializeField] Vector2 feildSize;
    [SerializeField] float moveSpeed = 1f;
    [SerializeField] float moveDistance = 1;

    Vector3 nextPosition;
    bool animationIsActive = false;

    public Vector3 GetNextPosition() { return nextPosition; }

    void Start()
    {
        AssignNextPosition();
        PopUp();
    }

    void Update() { if (!animationIsActive) MoveToNewPosition(); }

    void MoveToNewPosition()
    {
        transform.position = Vector3.MoveTowards(transform.position, nextPosition, moveSpeed);
        if(transform.position == nextPosition) PopUp();
    }

    void PopUp()
    {
        animationIsActive = true;
        animator.SetTrigger("StartAnimation");
        AssignNextPosition();
    }

    void ResetAnimationFlag() { animationIsActive = false; }

    void AssignNextPosition()
    {
        bool isTooClose = true;
        Vector3 newPosition = new Vector3(0,0,0);
        while(isTooClose)
        {
            newPosition = CalculatePosition(transform.position.y);
            if(Vector3.Distance(transform.position, newPosition) > moveDistance) isTooClose = false;
        }
        nextPosition = newPosition;

        Vector3 CalculatePosition(float yPos)
        {
            float xAxisValue = ((Random.value - .5f) * feildSize.x);
            float yAxisValue = transform.position.y;
            float zAxisValue = ((Random.value - .5f) * feildSize.y);
            return new Vector3(xAxisValue, yAxisValue, zAxisValue);
        }
    }
}
1 Like

I took me more than a day to find a solution for this task, and I’m still not proud of what I came with but it’s a good start for now, and maybe later I’ll refactor this solution.

I created a bunch of spawn points, and a new class

In the new class first I find all the enemies in the level and add it to a list, and also an array of spawn points. In the SpawnTimer I check that there are elements in the list and if so I set the state of the enemies to true. The other methods are helper methods to give me random spawn point and set the game object to true or false

public class SpawnCubesAtRandom : MonoBehaviour
{
    [HideInInspector] public int enemiesCount;
    [SerializeField] private Transform[] spawnPoints;
    public List<GameObject> enemies;

    [SerializeField] float waitTime = 2f;
    float startTime = 0;


    WaitForSecondsRealtime WaitForSeconds;
    [SerializeField] float waitTimeForCoroutine = 1.5f;

    private void Start()
    {
        WaitForSeconds = new WaitForSecondsRealtime(waitTimeForCoroutine);
        for (int i = 0; i < enemies.Count; i++)
        {
            SetEnemyActiveState(enemies[i].gameObject, false);
        }
        enemiesCount = enemies.Count;
    }

    private void Update()
    {
        SpawnTimer();
    }

    private void SpawnTimer()
    {
        startTime += Time.deltaTime;
        if (startTime >= waitTime)
        {
            if (enemiesCount >= 0)
            {
                foreach (var enemy in enemies)
                {
                    Vector3 offset = new Vector3(transform.position.x, .5f, transform.position.z);
                    SetEnemyActiveState(enemy.gameObject, true, enemy.transform.position + offset, enemy.transform.rotation);
                    startTime = 0;
                    StartCoroutine(TurnOffGameObject(enemy.gameObject));
                }
            }
        }
    }

    private Transform ReturnRandSpawnPoint()
    {
        int r = Random.Range(0, spawnPoints.Length);
        return spawnPoints[r];
    }

    private void SetEnemyActiveState(GameObject go, bool isActive)
    {
        go.SetActive(isActive);
    }

    private void SetEnemyActiveState(GameObject go, bool isActive, Vector3 pos, Quaternion quaternion)
    {
        go.SetActive(isActive);
        go.transform.position = ReturnRandSpawnPoint().position;
        go.transform.rotation = quaternion;
    }

    IEnumerator TurnOffGameObject(GameObject go)
    {
        yield return WaitForSeconds;
        SetEnemyActiveState(go, false);
    }
}
1 Like

This is the first time I’ve heard of [HideInInspector]. You sent me down a rabbit hole. :slight_smile:

As you shouldnt really have public fields in a class you shouldnt really need it … :stuck_out_tongue_winking_eye:

1 Like

I actually enjoyed this challenge, as it took me a little out of my comfort zone, and I had to do some real digging, but Im really happy with what Ive come up with… I created two new classes:
the first is a grid of way points:

{


    [Header("Grid Variables")]

    [SerializeField] int width = 20;
    [SerializeField] int height = 20;
    [SerializeField] GameObject tilePrefab;

    [Header("Grid Visualizer/Debugging")]
    [SerializeField] bool visualizeGrid = true; //Serialized to activate and Deactivate Grid visualization;
    [SerializeField] List<GameObject> tiles = new List<GameObject>();//serialized for debug purposes
    [SerializeField] List<Vector3> waypoints; //serialized for debug purposes
    
    public List<Vector3> Waypoints { get => waypoints; } //public access to Get waypoints



    private void Awake()
    {
        GenerateGrid();
    }

    private void Update()
    {
        //Checks if Visualization has been activated and enables/disables meshRenderers for tilePrefabs
        if (visualizeGrid == true) { VisualizeGrid(); }
        else { InvisibleGrid(); }

    }

    public void GenerateGrid()
    {
        //Creates a list of Vector3 grid waypoint coordinates, based on the size of the grid (Default is 20x20 to match the size of the Arena).
        for (int x = 0; x < width; x++)
        {
            for (int z = 0; z < height; z++)
            {
                waypoints.Add(new Vector3(x, -.47f, z));
            }

        }


        //creates a grid of cubes, 1 for each waypoint (Default is 400); This is inefficient, and is only being used for visualization purposes, should probably be done with a sprite renderer
        //instead
        for (int i = 0; i < waypoints.Count; i++)
        {
            var tile = Instantiate(tilePrefab, waypoints[i], Quaternion.identity, this.transform);
            tile.name = $"Waypoint {i}  = {waypoints[i]}";
            tile.GetComponent<MeshRenderer>().enabled = false;
            tiles.Add(tile);
        }
    }

    private void VisualizeGrid()
    {
        //enables MeshRenderer on grid cubes, for vizualization;
        foreach (GameObject tilePrefab in tiles)
        {
            tilePrefab.GetComponent<MeshRenderer>().enabled = true;
        }
    }
    private void InvisibleGrid()
    {
        //disables MeshRenderer on grid cubes, when vizualiztion of the grid is not needed.
        foreach (GameObject tilePrefab in tiles)
        {
            tilePrefab.GetComponent<MeshRenderer>().enabled = false;
        }
    }

}

The second is an EnemyMover, it decides a random waypoint on the grid, and moves to that location, pops up and down, decides a new random location on the grid, and repeats…

{
    [Header("Variable Setting")]
    
    [SerializeField] float locationDelay = 2.0f;

    WaypointGrid grid;
    Animator animator;
    List<Vector3> waypoints;
    Vector3 nextLocation;


    void Start()
    {
        animator = GetComponent<Animator>();
        grid = FindObjectOfType<WaypointGrid>();

        //Gets the list of waypoints Generated by the WaypointGrid;
        waypoints = grid.Waypoints;

        //Chooses a random location within the grid to move to
        StartCoroutine(ChangeLocation());

    }
    public IEnumerator ChangeLocation()
    {
        //chooses a Random number based on the number of waypoints created, then uses that number to determine its next spawning location.
        int randomWaypoint = Random.Range(0, waypoints.Count);
        nextLocation = new Vector3(waypoints[randomWaypoint].x, waypoints[randomWaypoint].y + 1f, waypoints[randomWaypoint].z) ;
        transform.position = nextLocation;

        //plays the "Pop up" animation
        animator.Play("Pop Up");
        
        //waits for animation to finish and restarts the process.
        yield return new WaitForSeconds(locationDelay);
        StartCoroutine(ChangeLocation());
    }
   
}

The grid of waypoints also generated a Grid of cubes to help with visualization purposes, that can be turned on or off in the inspector. That helped me get the arena and all other assets aligned with the grid coordinates.

1 Like

A nice option.

However from a gameplay point of view it may become annoying for the player if the mole keeps (randomly) appearing on the far side of the grid and there is no chance of getting to it.
May be an option is to choose a random waypoint at a limited distance from where the mole is.
See what happens when you play it…