Forum begins after the advertisement:


[Part 2] MapController not updating the current chunk

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 2] MapController not updating the current chunk

Viewing 14 posts - 1 through 14 (of 14 total)
  • Author
    Posts
  • #17217
    anon (Æternus Lux)
    Level 4
    Participant
    Helpful?
    Up
    0
    ::

    Hello I am having an Issue with part 2 of the tutorial where the map controller is not updating the current chunk when spawning new chunks causing chunks to cease spawning after the first chunks surrounding the starting chunk have been spawned as far as I can tell my code is identical to the source material other than I am using a player action map for the movement system which as far as I know should not cause any issues but I am stating it anyway. this is my map controller code and my chunk trigger code below also I have confirmed that all settings in unity are the same as the source material so I am relatively sure the problem is somewhere in the code

    edit i forgot to mention while i was trying to debug I changed the ontriggerstay to on trigger enter but the code has the same issue regardless of which one I use

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class MapController : MonoBehaviour
    {
        public List<GameObject> terrainChunks;
        public GameObject player;
        public float checkerRadius;
        Vector3 noTerrainPosition;
        public LayerMask terrainMask;
        public GameObject currentChunk;
        Player pm;
    
    
        // Start is called before the first frame update
        void Start()
        {
            pm = FindObjectOfType<Player>();
        }
    
        // Update is called once per frame
        void Update()
        {
            ChunkChecker();
            if(!currentChunk)
            {
                return;
            }
        }
        public void ChunkChecker()
        {
            Debug.Log("ChunkChecker called. currentChunk is:" + (currentChunk != null ? currentChunk.name : "null"));
            if (!currentChunk)
            {
                return;
            }
            if (pm.MoveInput.x > 0 && pm.MoveInput.y == 0) //right
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Right").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Right").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x < 0 && pm.MoveInput.y == 0) //left
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Left").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Left").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x == 0 && pm.MoveInput.y > 0) //up
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Up").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Up").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x == 0 && pm.MoveInput.y < 0) //down
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Down").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Down").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x > 0 && pm.MoveInput.y > 0) //right up
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Right Up").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Right Up").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x > 0 && pm.MoveInput.y < 0) //right down
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Right Down").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Right Down").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x < 0 && pm.MoveInput.y > 0) //left up
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Left Up").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Left Up").position;
                    SpawnChunk();
                }
            }
            else if (pm.MoveInput.x < 0 && pm.MoveInput.y < 0) //left down
            {
                if (!Physics2D.OverlapCircle(currentChunk.transform.Find("Left Down").position, checkerRadius, terrainMask))
                {
                    noTerrainPosition = currentChunk.transform.Find("Left Down").position;
                    SpawnChunk();
                }
            }
        }
        void SpawnChunk()
        {
            int rand = Random.Range(0, terrainChunks.Count);
            Instantiate(terrainChunks[rand], noTerrainPosition, Quaternion.identity);
        }
    }```
    

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

    public class ChunkTrigger : MonoBehaviour { MapController mc; public GameObject targetMap;

    // Start is called before the first frame update
    void Start()
    {
        mc = FindObjectOfType<MapController>();
        if (mc == null )
        {
            Debug.Log("map controller not found!");
        }
    }
    
    private void OnTriggerEnter2D(Collider2D col) // Use OnTriggerEnter2D
    {
        if (col.CompareTag("Player") && mc != null)
        {
            Debug.Log("player entered trigger for:"+ targetMap.name);
            mc.currentChunk = targetMap; // Set currentChunk
            Debug.Log("currentChunk is now:" + mc.currentChunk.name);
            mc.ChunkChecker(); // Call ChunkChecker immediately
        }
    }
    
    private void OnTriggerExit2D(Collider2D col)
    {
        if (col.CompareTag("Player") && mc != null && mc.currentChunk == targetMap)
        {
            // Did NOT set currentChunk to null here.
            // Let the MapController handle the case where there is no current chunk.
        }
    }

    }“`

    and for reference here is my player controller code

    
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.EventSystems;
    using UnityEngine.InputSystem;
    
    public class Player : MonoBehaviour
    {
    
        private PlayerInputMap _input;
        public Vector2 MoveInput { get; private set; }
        // Start is called before the first frame update
        void Start()
        {
            _input = new PlayerInputMap();
            _input.Player.Enable();
    
        }
    
        // Update is called once per frame
        void Update()
        {
            MoveInput = _input.Player.Walk.ReadValue<Vector2>();
    
            transform.Translate(MoveInput * Time.deltaTime *8);
        }
    }```
    #17218
    Lukas Kazda
    Level 17
    Gold Supporter (Patron)
    Helpful?
    Up
    1
    ::

    Hi, i had the same issue as you, and i think to remember it was a editor problem. I would double check all prefabs, the ones that you already have dragged into your world as well as the saved prefabs. Cant find any difference in your code compared to mine

    has upvoted this post.
    #17219
    Lukas Kazda
    Level 17
    Gold Supporter (Patron)
    Helpful?
    Up
    1
    ::

    Another thing i can think of is a missing boxcollider (not set to trigger) on your player object

    has upvoted this post.
    #17229
    anon (Æternus Lux)
    Level 4
    Participant
    Helpful?
    Up
    1
    ::

    I’ll take another look I’m not sure if I checked the prefabs so hopefully that is the problem

    has upvoted this post.
    #17230
    anon (Æternus Lux)
    Level 4
    Participant
    Helpful?
    Up
    1
    ::

    I was missing the rigidbody2d lol thanks for the help you got me looking at the right part of the inspector to see what i missed

    has upvoted this post.
    #17231
    Lukas Kazda
    Level 17
    Gold Supporter (Patron)
    Helpful?
    Up
    1
    ::

    Tag and Boxcollider2D on player gameobject fine as well?

    has upvoted this post.
    #17232
    Lukas Kazda
    Level 17
    Gold Supporter (Patron)
    Helpful?
    Up
    1
    ::

    “Debug.Log(“player entered trigger for:”+ targetMap.name);” Does this line print its output to the console when entering a new chunk? in chunktrigger script in ontriggerenter function

    has upvoted this post.
    #17236
    anon (Æternus Lux)
    Level 4
    Participant
    Helpful?
    Up
    1
    ::

    turns out I was missing the rigidbody 2d so you pretty much hit the nail on the head I only noticed it because you had me check the trigger on the box collider lol I forgot to add one I went back and watched his player set up and checked everything he did and I missed that part while I was sipping my coffee i guess lol

    has upvoted this post.
    #17296
    Jukers
    Level 9
    Bronze Supporter (Patron)
    Helpful?
    Up
    0
    ::

    I think i have the same problem, but my player configuration is correct. any ideas of what it could be?

    #17297
    Lukas Kazda
    Level 17
    Gold Supporter (Patron)
    Helpful?
    Up
    1
    ::

    Hi Jukers, can you add the Debug.Log() Lines in your Chunktrigger script, in your OnTriggerEnter2D function? and tell us pls if it prints anything on the console

    
    private void OnTriggerEnter2D(Collider2D col) // Use OnTriggerEnter2D
    {
        if (col.CompareTag("Player") && mc != null)
        {
            Debug.Log("player entered trigger for:"+ targetMap.name); //add this for debugging
            mc.currentChunk = targetMap; // Set currentChunk
            Debug.Log("currentChunk is now:" + mc.currentChunk.name); //add this for debugging
            mc.ChunkChecker(); // Call ChunkChecker immediately
        }
    }
    
    has upvoted this post.
    #17300
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    @jukers if you can share your code as well, it will be great.

    #17322
    Alp Apustaja
    Level 3
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    It looks like you’re trying to debug the OnTriggerEnter2D function in your chunk trigger script to ensure that the trigger is working correctly. Here are a few suggestions to help you troubleshoot the issue:

    1. Check Collider Settings: Ensure that the collider on your player object is set up correctly. The BoxCollider2D should not be set as a trigger if you want it to interact with non-trigger colliders. Also, ensure that the chunk trigger collider is set as a trigger.

    2. Layer Collision Matrix: Make sure that the layers of your player and the chunk trigger are set up to interact with each other. You can check this in the Unity Physics settings (Edit > Project Settings > Physics2D).

    3. Debugging Output: Based on the code you provided, the Debug.Log statements should print messages to the console when the player enters the trigger. If you’re not seeing any messages:

      • Ensure that the targetMap is not null when the trigger is activated.
      • Check if the OnTriggerEnter2D function is being called at all. You can add a Debug.Log("Trigger entered") at the start of the function to verify this.
    4. Compare Tags: Make sure that the player’s GameObject has the tag “Player” set correctly. You can do this in the Inspector for the player GameObject. It should match exactly, including capitalization.

    5. Review Prefabs: Since you mentioned prefabs, double-check that all prefab instances in the scene are correctly configured and that there are no issues in the prefab itself that could be causing the problem.

    6. Test with a Simple Collider: As a quick test, you could create a simple GameObject with a BoxCollider2D set as a trigger and see if it detects the player. This can help isolate whether the issue is with the chunk trigger setup or something else.

    If you’ve gone through these steps and are still having issues, please share any additional relevant code or information about your setup, and I’d be happy to help further!

    #17327
    Alp Apustaja
    Level 3
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    It sounds like you’re facing an issue with a player configuration. To help you better, I need more information about the specific problem you’re encountering. Here are a few questions that might help to narrow it down:

    1. What platform or framework are you using? (e.g., Unity, Unreal Engine, a specific game engine, etc.)

    2. What specific issue are you experiencing? (e.g., player not moving, animations not playing, settings not saving, etc.)

    3. Could you share any relevant code snippets or configuration settings? This will help identify if there’s an error in the code or settings.

    4. Have you checked for any error messages or logs? If so, what do they say?

    5. What have you tried so far to resolve the issue?

    Once I have more details, I’ll be better equipped to assist you!

    #17331
    Alp Apustaja
    Level 3
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    I’m glad to hear that you figured out the issue with the missing Rigidbody2D component! It’s quite common to overlook small setup details, especially when you’re focused on coding.

    Just to recap for future reference, here are some key points to consider when working with Unity and triggers:

    1. Rigidbody2D Component: For 2D triggers to work correctly, the GameObject with the Collider needs to have a Rigidbody2D component attached. This component is essential for the physics engine to recognize and handle collisions and triggers.

    2. Collider Settings: Ensure that the Collider components are set up correctly. For triggers, make sure the “Is Trigger” checkbox is checked on the Collider.

    3. Layer Collision Matrix: Double-check the Layer Collision Matrix in Unity’s Physics2D settings to ensure that the layers of your player and chunks can interact.

    4. Movement Logic: In your player controller, make sure that the movement logic is not affecting the trigger detection. If you’re using transform.Translate, it might bypass physics calculations, especially if the Rigidbody2D is set to Kinematic. Consider using Rigidbody2D’s MovePosition or applying forces for movement if you want to maintain full physics interactions.

    5. Debugging: Using Debug.Log statements, as you’ve done, is a great way to trace what’s happening in your code. It helps to confirm whether specific sections are being executed as expected.

    If you run into any further issues or have additional questions as you continue with your tutorial, feel free to ask! Happy coding!

Viewing 14 posts - 1 through 14 (of 14 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: