SchultzGames
Para tirar dúvidas, crie um tópico especifico na área "Dúvidas em Geral" e aguarde ser respondido. Evite comentar em tópicos não relacionados a sua dúvida :D
TÓPICOS RECENTES:
Tópico:
Postado em:
Postado por:
ShapeKeys do Blender para a Unity altera áreas próximas
COMO EVITAR QUE UM OBJETO (PLAYER,ITEM ETC...) ATRAVESSE UMA PAREDE.
Ajuda em Script de Verificação de Ação e Reação
unity Failed to load PlayerSettings (internal index #0). Most likely data f
modelar avatar e skins para um jogo web
PRECISO FAZER QUE MEU GAME FIQUE ONLINE
Materiais do Blander não aparecem no MeshRendere do Objeto na Unity
Repetiçoes de Textura no Terreno
SERVER IS DOWN - UNITY+MSQL
Procuro programadores - Novo jogo
Problema com o MS VEHICLES
Preciso de ajuda com a Unity
Problema com vídeo em 360° na Unity
Problemas no MS Vehicles
unity- eventos na Animação com Armature/Bones vinda do blender não funciona
ajuda exibir resultados simulados em uma liga Game Unity
Unity - ParticleSystem não é redirecionado no rawimage no canvas
Como resolver o problema de "face orientation" no Blender.
[DÚVIDA] Tive um problema com meu Canvas
erro na Directional Light
Problemas com o Directional Light da Unity 3D
210 Linhas de código para inimigo é muito grande?
Novo jogo da franquia Sphere game em desenvolvimento
malha da roda não girando com wheel collider unity
Problemas com ambiguidade
Touch mobile
INVALID TOKEN
Como acessar o "HD Render Pipeline" do HDRP por script?
CHAT GPT PRA JOGO DE TIRO? comentem
Tutorial script inimigo segue e foge do player
Ainda vale a pena lançar Asset na Asset Store?
Ajuda com tabela de historico de pontuaçao.
[TUTORIAL] Entrar no carro estilo GTA
Como derrapar um Whell Collider
Como altertar o valor do "Asymptote Value" do Whell Collider via Script
Preciso de ajuda para substituir valor de variavel em outro script
Ajuda com Top Down Shooter utilizando Photon
Duvida com Netcode
[RESOLVIDO] Unity - Movendo a Câmera na Horizontal/Vertical com Touch
Alguém me ajuda com os anúncios pfv
Segundo Trailer do jogo Dark Age, Feliz Natal a todos!
Unity - ScrollRect, Viewport, Content - O Conteúdo ñ inicia no topo
Coleta de itens
Unity - Cadastro do email do jogador
[GRATIS] PACK DE MODELOS 3D PARA JOGO DE TERROR
Onde Conseguir músicas para meu Jogo?
error CS0246 em Script
Alguem teve ja esse problema?
[Projeto em Andamento] Draug, um jogo de hordas
DISPONIVEL PARA FAZER MODELOS 3D
Unity-Loja.Como os Jogadores terão acesso aos ítens comprados na PlayStore?
Bugando depois do Build.
Primeiro Trailer do jogo Dark Age
Problema com sombra
Mesh e Material do objeto trocando para uma instancia no inicio do jogo
[RESOLVIDO] Unity - RawImages_Layer_Camera
INVESTIMENTO EM JOGOS E BANCO DE TALENTO
Teaser do meu novo projeto pessoal, Dark Age
Preciso de ajuda com mudança para mobile androide.
[RESOLVIDO] Posição final do objeto em jogo 2D
Input.GetAxis() obedercer a orientação de um objeto.
Interação com elementos UI
Meu primeiro jogo na steam
Minimap/Radar/GPS Estilo GTA V
[RESOLVIDO] Erro no console depois que formatei o pc
PACK GRÁTIS de Músicas ELETRÔNICAS para ajudar vocês em seus Jogos Indies!
[TUTORIAL] Entenda como funciona: ENUM, SWITCH, BREAK, CASE no C#
O Labirinto II - Baixe o Jogo
Qual e o codigo de Botões na unity para saber seus estados?
Como carregar itens pequenos dentro do carro sem que atravesse os colliders
[Duvida] Script pegar itens
Travamento ao trocar de cena
Colisão zoada e movimentação
Salvar objetos que foram destruidos entre cenas na unity
Quero começa a desenvolver um jogo de luta porem eu queria aprender a faze
Pegar qual objeto colidiu com o Linecast.
movimentação e camera?
[RESOLVIDO] Unity - SceneManager.LoadScene abre scene com objeto "vazio"
[RESOLVIDO] ajuda sobre skybox
MEU SIMULADOR DE CARRO
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY
[RESOLVIDO] Ausencia da funçao NavMesh na Unity 2022.2.12
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY - 2
Roll Up Um jogo de aventura e desáfios
Terminologia da Unity em outras engines
Como criar a iluminação do Sol no Sistema Solar?
Conexão de lobby pelo OnConnectedToMaster
Problema na exportção de projeto unity
[RESOLVIDO] Unity - Áudios estão emitindo som só Depois do Botão ser solto
Unity - Banco de Dados Online junto ao Jogo
Player virar para o inimigo(Prefab)
[TUTORIAL] Sistema De Save Game Ao Sair Da Fase
Problema de Sincronização de um objeto de um jogo multiplayer usa q Photon
Unity - Compartilhar meu Jogo
Alguém que manja do Google ADmob?
Unity - Avaliar meu Jogo
[RESOLVIDO] Destruir inimigo com o player.
Salvar e carregar dados na Unity de objetos prefabs sem sobrescrever os dad
Unity - Salvar os Dados do Jogador Online
Hoje à(s) 10:09 pm
Dom Mar 10, 2024 2:30 pm
Sex Mar 01, 2024 1:27 pm
Qui Fev 22, 2024 9:57 pm
Qua Fev 21, 2024 10:39 am
Ter Fev 20, 2024 9:28 am
Ter Fev 20, 2024 12:15 am
Seg Fev 19, 2024 1:06 pm
Seg Fev 12, 2024 1:56 pm
Seg Fev 12, 2024 1:17 pm
Dom Fev 11, 2024 8:55 pm
Dom Fev 11, 2024 11:16 am
Seg Fev 05, 2024 4:18 pm
Dom Fev 04, 2024 9:39 pm
Qua Jan 31, 2024 11:59 pm
Ter Jan 30, 2024 7:37 pm
Ter Jan 23, 2024 6:33 pm
Dom Jan 21, 2024 6:03 pm
Sáb Jan 20, 2024 7:03 pm
Sáb Jan 20, 2024 6:58 pm
Sáb Jan 20, 2024 6:39 pm
Sex Jan 19, 2024 1:29 pm
Sex Jan 19, 2024 8:40 am
Dom Jan 14, 2024 5:30 pm
Qua Jan 10, 2024 10:29 pm
Qua Jan 10, 2024 8:55 pm
Qua Jan 10, 2024 7:14 pm
Ter Jan 09, 2024 3:55 pm
Ter Jan 09, 2024 8:04 am
Sáb Jan 06, 2024 8:02 pm
Sex Jan 05, 2024 7:01 am
Sex Jan 05, 2024 12:12 am
Qui Jan 04, 2024 6:55 pm
Qui Jan 04, 2024 12:52 pm
Qui Jan 04, 2024 4:34 am
Ter Jan 02, 2024 11:48 pm
Dom Dez 31, 2023 7:25 pm
Qua Dez 27, 2023 5:44 pm
Qua Dez 27, 2023 3:08 pm
Sáb Dez 23, 2023 7:27 pm
Sáb Dez 23, 2023 5:06 pm
Qui Dez 21, 2023 8:10 pm
Seg Dez 18, 2023 2:04 pm
Sex Dez 15, 2023 5:11 pm
Qui Dez 14, 2023 9:13 pm
Qui Dez 14, 2023 2:47 pm
Qui Dez 14, 2023 1:48 pm
Qua Dez 13, 2023 8:58 pm
Ter Dez 12, 2023 2:32 pm
Seg Dez 11, 2023 1:53 pm
Qua Dez 06, 2023 8:13 pm
Sáb Dez 02, 2023 8:06 pm
Qui Nov 30, 2023 7:49 am
Seg Nov 27, 2023 1:35 am
Qua Nov 22, 2023 7:37 am
Qui Nov 09, 2023 1:22 pm
Seg Nov 06, 2023 11:59 am
Ter Out 31, 2023 9:53 am
Dom Out 29, 2023 8:05 pm
Dom Out 29, 2023 3:03 am
Sex Out 27, 2023 3:43 pm
Sex Out 27, 2023 3:28 pm
Qua Out 25, 2023 1:20 pm
Seg Out 23, 2023 10:34 am
Dom Out 22, 2023 6:55 pm
Qui Out 19, 2023 11:57 pm
Qui Out 19, 2023 6:39 pm
Ter Out 17, 2023 6:37 pm
Ter Out 17, 2023 6:18 pm
Seg Out 16, 2023 1:59 pm
Sáb Out 14, 2023 12:15 pm
Qua Out 11, 2023 6:07 pm
Seg Out 09, 2023 4:19 pm
Qua Out 04, 2023 12:12 pm
Qua Out 04, 2023 12:11 pm
Ter Out 03, 2023 9:18 pm
Ter Out 03, 2023 9:08 pm
Ter Out 03, 2023 6:05 pm
Ter Set 26, 2023 12:45 pm
Seg Set 25, 2023 9:02 pm
Seg Set 25, 2023 9:47 am
Sáb Set 23, 2023 2:10 pm
Sex Set 22, 2023 9:01 pm
Qui Set 21, 2023 11:04 am
Qua Set 20, 2023 4:40 pm
Qua Set 20, 2023 9:15 am
Dom Set 17, 2023 12:17 pm
Sex Set 15, 2023 7:24 pm
Sex Set 15, 2023 5:41 pm
Sex Set 15, 2023 4:28 pm
Sex Set 15, 2023 10:56 am
Sex Set 15, 2023 10:15 am
Seg Set 11, 2023 11:43 am
Seg Set 11, 2023 11:31 am
Sáb Set 09, 2023 4:53 pm
Sáb Set 09, 2023 1:44 pm
Ter Set 05, 2023 11:12 pm
Ter Set 05, 2023 3:12 pm
Seg Set 04, 2023 11:53 pm



































































































Ajuda com script movimento por Grid Tile no Navmesh

3 participantes

Ir para baixo

PEDIDO Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Qui Out 04, 2018 11:41 am

Bom dia Pessoal !

Sou novo aki no forum mas um grande fã de jogos RPG's e do Unity.
Estou fazendo meu mmorpg e preciso de uma ajudinha. Estou precisando arrumar o movimento
do player e dos mobs.
Estou usando o Navigation2D da assets store que faz um navmesh para 2D. OK ele funciona perfeitamente, mas gostaria
que o player e os mobs se movimentassem por Grid Tile, ou seja, sem diagonal e parar sempre no centro do Tile. Mesmo sistema de movimento do jogo Tibia para quem conhece Smile
Para fazer o mapa estou usando o recurso do Tilemap do Unity ai depois uso o Navigation2D para gerar a malha do navmesh
e o player desviar automaticamente dos obstáculos.
Não sei se preciso alterar o script do Navigation2D ou do movimento do player e como alterar o algorítimo, por isso preciso de ajuda.

Gostaria que o movimento fosse algo parecido com isso:

https://youtu.be/RPmuCtcldBg
https://github.com/Chris85bh/Navigation2D

Desde já agradeço.
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Qui Out 04, 2018 6:29 pm

Desculpem. Esqueci de postar os Scripts para vocês me ajudarem.

Essa é a parte do script do player para o movimento por clique no mapa e usando o teclado. A parte de usar o teclado eu alterei para não usar a diagonal mas não consegui fazer para o player parar sempre no centro do tile.
Código:
void SelectionHandling()
    {
 
        // click raycasting if not over a UI element & not pinching on mobile
        // note: this only works if the UI's CanvasGroup blocks Raycasts
        if (Input.GetMouseButtonDown(0) && !Utils.IsCursorOverUserInterface() && Input.touchCount <= 1)
        {
            // cast a 3D ray from the camera towards the 2D scene.
            // Physics2D.Raycast isn't made for that, we use GetRayIntersection.
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            // raycast with local player ignore option
            RaycastHit2D hit = localPlayerClickThrough ? Utils.Raycast2DWithout(ray, gameObject) : Physics2D.GetRayIntersection(ray);


            // valid target?
            Entity entity = hit.transform != null ? hit.transform.GetComponent<Entity>() : null;
            if (entity)
            {
                // set indicator
                SetIndicatorViaParent(hit.transform);

                // clicked last target again? and is not self or pet?
                if (entity == target && entity != this && entity != activePet)
                {
                    // attackable? => attack
                    if (CanAttack(entity))
                    {
                        // cast the first skill (if any, and if ready)
                        if (skills.Count > 0 && skills[0].IsReady())
                            CmdUseSkill(0);
                        // otherwise walk there if still on cooldown etc
                        // use collider point(s) to also work with big entities
                        else
                            CmdNavigateDestination(entity.collider.ClosestPointOnBounds(transform.position), skills.Count > 0 ? skills[0].castRange : 0f);
                    }
                    // npc & alive => talk
                    else if (entity is Npc && entity.health > 0)
                    {
                        // close enough to talk?
                        // use collider point(s) to also work with big entities
                        if (Utils.ClosestDistance(collider, entity.collider) <= interactionRange)
                            FindObjectOfType<UINpcDialogue>().Show();
                        // otherwise walk there
                        // use collider point(s) to also work with big entities
                        else
                            CmdNavigateDestination(entity.collider.ClosestPointOnBounds(transform.position), interactionRange);
                    }
                    // monster & dead => loot
                    else if (entity is Monster && entity.health == 0)
                    {
                        // has loot? and close enough?
                        // use collider point(s) to also work with big entities
                        if (((Monster)entity).HasLoot() &&
                            Utils.ClosestDistance(collider, entity.collider) <= interactionRange)
                            FindObjectOfType<UILoot>().Show();
                        // otherwise walk there
                        // use collider point(s) to also work with big entities
                        else
                            CmdNavigateDestination(entity.collider.ClosestPointOnBounds(transform.position), interactionRange);
                    }

                    // addon system hooks
                    Utils.InvokeMany(typeof(Player), this, "OnSelect_", entity);
                // clicked a new target
                }
                else
                {
                    // target it
                    CmdSetTarget(entity.netIdentity);
                }
            }
            // if we hit nothing then we want to move somewhere
            else
            {
 
                // set indicator and navigate to the nearest walkable
                // destination. this prevents twitching when destination is
                // accidentally in a room without a door etc.
                Vector2 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector2 bestDestination = agent.NearestValidDestination(worldPos);
                SetIndicatorViaPosition(bestDestination);
 CmdNavigateDestination (bestDestination, 0);

            }
        }
    }

void WSADHandling()
    {
        // don't move if currently typing in an input
        // we check this after checking h and v to save computations
        if (!UIUtils.AnyInputActive())
        {
            // get horizontal and vertical input
            // note: no != 0 check because it's 0 when we stop moving rapidly
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");

            // create direction, normalize in case of diagonal movement
            Vector2 direction = new Vector2(horizontal, vertical);

            if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
            {
                direction.y = 0;
            }
            else
            {
                direction.x = 0;
            }

            //if (direction.magnitude > 1) direction = direction.normalized;

            // draw direction for debugging
            Debug.DrawLine(transform.position, transform.position + (Vector3)direction, Color.green, 0, false);

            // clear indicator if there is one, and if it's not on a target
            // (simply looks better)
            if (direction != Vector2.zero && indicator != null && indicator.transform.parent == null)
                Destroy(indicator);

            // send to server - if changed since last time to save bandwidth
            if (direction != lastDirection)
            {
                CmdNavigateVelocity(direction);
                lastDirection = direction;
            }
        }
    }


E esse é o script do Navigation2D para gerar o navmesh no mapa 2D:

Código:
using UnityEditor;
using UnityEditor.AI;
using UnityEngine;
using UnityEngine.AI;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.Tilemaps;
#endif
using System.Collections.Generic;
using System.Linq;

public class Navigation2D : EditorWindow
{
    // options
    float navmeshExtends = 1;
    static int drawMode = 0; // 0 = wireframe, 1 = full

    bool IsValidCollider(Collider2D co)
    {
        // usable for navmesh generation if not trigger and if navigation static
        bool navstatic = GameObjectUtility.AreStaticEditorFlagsSet(co.gameObject, StaticEditorFlags.NavigationStatic);
        return navstatic && co.enabled && !co.isTrigger;
    }

    // set area as not walkable so that huge objects dont get walkable areas
    // inside of them
    void MakeUnwalkable(GameObject go)
    {
        int layer = GameObjectUtility.GetNavMeshAreaFromName("Not Walkable");
        GameObjectUtility.SetNavMeshArea(go, layer);
    }

    void AddBoxCollider2Ds(Transform parent)
    {
        // find all valid colliders, add them to projection
        var colliders = GameObject.FindObjectsOfType<BoxCollider2D>();
        var filtered = colliders.Where(co => IsValidCollider(co)).ToList();
        foreach (var collider in filtered)
        {
            // note: creating a primitive is necessary in order for it to bake properly
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go.isStatic = true;
            go.transform.parent = parent;
            // position via offset and transformpoint
            var localPos = new Vector3(collider.offset.x, collider.offset.y, 0);
            var worldPos = collider.transform.TransformPoint(localPos);
            go.transform.position = new Vector3(worldPos.x, 0, worldPos.y);
            // scale depending on scale * collider size (circle=radius/box=size/...)
            go.transform.localScale = NavMeshUtils2D.ScaleFromBoxCollider2D(collider);
            // rotation
            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(collider.transform.eulerAngles));

            MakeUnwalkable(go);
        }
    }

    void AddCircleCollider2Ds(Transform parent)
    {
        // find all valid colliders, add them to projection
        var colliders = GameObject.FindObjectsOfType<CircleCollider2D>();
        var filtered = colliders.Where(co => IsValidCollider(co)).ToList();
        foreach (var collider in filtered)
        {
            // note: creating a primitive is necessary in order for it to bake properly
            var go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
            go.isStatic = true;
            go.transform.parent = parent;
            // position via offset and transformpoint
            var localPos = new Vector3(collider.offset.x, collider.offset.y, 0);
            var worldPos = collider.transform.TransformPoint(localPos);
            go.transform.position = new Vector3(worldPos.x, 0, worldPos.y);
            // scale depending on scale * collider size (circle=radius/box=size/...)
            go.transform.localScale = NavMeshUtils2D.ScaleFromCircleCollider2D(collider);
            // rotation
            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(collider.transform.eulerAngles));

            MakeUnwalkable(go);
        }
    }

    void AddPolygonCollider2Ds(Transform parent)
    {
        // find all valid colliders, add them to projection
        var colliders = GameObject.FindObjectsOfType<PolygonCollider2D>();
        var filtered = colliders.Where(co => IsValidCollider(co)).ToList();
        foreach (var collider in filtered)
        {
            // note: creating a primitive is necessary in order for it to bake properly
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go.isStatic = true;
            go.transform.parent = parent;

            // position via offset and transformpoint
            var localPos = new Vector3(collider.offset.x, collider.offset.y, 0);
            var worldPos = collider.transform.TransformPoint(localPos);
            go.transform.position = new Vector3(worldPos.x, 0, worldPos.y);
            // scale depending on scale * collider size (circle=radius/box=size/...)
            go.transform.localScale = NavMeshUtils2D.ScaleFromPolygonCollider2D(collider);
            // rotation
            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(collider.transform.eulerAngles));

            // remove box collider. note that baking uses the meshfilter, so
            // the collider doesn't really matter anyway.
            DestroyImmediate(go.GetComponent<BoxCollider>());

            // Use the triangulator to get indices for creating triangles
            int[] indices = Triangulation.Triangulate(collider.points.ToList()).ToArray();

            // convert vector2 points to vector3 vertices
            var vertices = collider.points.Select(p => new Vector3(p.x, 0, p.y)).ToList();

            // create mesh
            var mesh = new Mesh();
            mesh.vertices = vertices.ToArray();
            mesh.triangles = indices;
            //mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            // assign it to the mesh filter
            go.GetComponent<MeshFilter>().sharedMesh = mesh;

            MakeUnwalkable(go);
        }
    }

    void AddEdgeCollider2Ds(Transform parent)
    {
        // find all valid colliders, add them to projection
        var colliders = GameObject.FindObjectsOfType<EdgeCollider2D>();
        var filtered = colliders.Where(co => IsValidCollider(co)).ToList();
        foreach (var collider in filtered)
        {
            // note: creating a primitive is necessary in order for it to bake properly
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go.isStatic = true;
            go.transform.parent = parent;

            // position via offset and transformpoint
            var localPos = new Vector3(collider.offset.x, collider.offset.y, 0);
            var worldPos = collider.transform.TransformPoint(localPos);
            go.transform.position = new Vector3(worldPos.x, 0, worldPos.y);
            // scale depending on scale * collider size (circle=radius/box=size/...)
            go.transform.localScale = NavMeshUtils2D.ScaleFromEdgeCollider2D(collider);
            // rotation
            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(collider.transform.eulerAngles));

            // remove box collider. note that baking uses the meshfilter, so
            // the collider doesn't really matter anyway.
            DestroyImmediate(go.GetComponent<BoxCollider>());

            // create mesh from edgecollider2D by stepping through each point
            // and creating a triangle with point, point-1 and point-1 with y=1
            List<Vector3> vertices = new List<Vector3>();
            List<int> indices = new List<int>();

            // start at 2nd point so we can use the first one in our triangle,
            for (int i = 1; i < collider.points.Length; ++i)
            {
                Vector2 a2D = collider.points[i-1];
                Vector2 b2D = collider.points[i];

                // convert to 3D
                //   point A
                //   point B
                //   point C := A with y+1
                Vector3 a3D = new Vector3(a2D.x, 0, a2D.y);
                Vector3 b3D = new Vector3(b2D.x, 0, b2D.y);
                Vector3 c3D = new Vector3(a2D.x, 1, a2D.y);

                // add 3 vertices
                vertices.Add(a3D);
                vertices.Add(b3D);
                vertices.Add(c3D);

                // add last 3 vertices as indices
                indices.Add(vertices.Count - 1);
                indices.Add(vertices.Count - 2);
                indices.Add(vertices.Count - 3);
            }

            // create mesh
            var mesh = new Mesh();
            mesh.vertices = vertices.ToArray();
            mesh.triangles = indices.ToArray();
            //mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            // assign it to the mesh filter
            go.GetComponent<MeshFilter>().sharedMesh = mesh;

            MakeUnwalkable(go);
        }
    }

#if UNITY_2017_2_OR_NEWER
    void AddTilemapCollider2Ds(Transform parent)
    {
        // find all grids
        Grid[] grids = GameObject.FindObjectsOfType<Grid>();
        foreach (Grid grid in grids)
        {
            // find tilemaps (we only care about those that have colliders)
            var tilemaps = grid.GetComponentsInChildren<Tilemap>().Where(
                tm => tm.GetComponent<TilemapCollider2D>()
            ).ToList();

            foreach (Tilemap tilemap in tilemaps)
            {
                // go through each cell
                BoundsInt bounds = tilemap.cellBounds;
                for (int y = bounds.position.y; y < bounds.size.y; ++y)
                {
                    for (int x = bounds.position.x; x < bounds.size.x; ++x)
                    {
                        // find out if it has a collider
                        Vector3Int cellPosition = new Vector3Int(x, y, 0);
                        if (tilemap.GetColliderType(cellPosition) != Tile.ColliderType.None)
                        {
                            // convert to world space
                            Vector3 worldPosition = tilemap.GetCellCenterWorld(cellPosition);

                            // note: creating a primitive is necessary in order for it to bake properly
                            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                            go.isStatic = true;
                            go.transform.parent = parent;
                            // position via offset and transformpoint
                            go.transform.position = new Vector3(worldPosition.x, 0, worldPosition.y);
                            // scale depending on scale * collider size (circle=radius/box=size/...)
                            go.transform.localScale = NavMeshUtils2D.ScaleTo3D(tilemap.transform.localScale);
                            // rotation
                            go.transform.rotation = Quaternion.Euler(NavMeshUtils2D.RotationTo3D(tilemap.transform.eulerAngles));

 MakeUnwalkable(go);
                        }
                    }
                }
            }
        }
    }
#endif

    void BakeNavMesh2D()
    {
        // create a temporary parent GameObject
        var obj = new GameObject();

        // find all static box colliders, add them to projection
        AddBoxCollider2Ds(obj.transform);
        // find all static circle colliders, add them to projection
        AddCircleCollider2Ds(obj.transform);
        // find all static polygon colliders, add them to projection
        AddPolygonCollider2Ds(obj.transform);
        // find all edge polygon colliders, add them to projection
        AddEdgeCollider2Ds(obj.transform);
        // find all tilemap colliders, add them to projection
#if UNITY_2017_2_OR_NEWER
        AddTilemapCollider2Ds(obj.transform);
#endif

        // min and max point from 2D colliders projected to 3D.
        // (scanning through 3D colliders doesn't work well because the polygon
        //  GameObjects are pure meshes without colliders)
        var cols = GameObject.FindObjectsOfType<Collider2D>();
        if (cols.Length > 0)
        {
            var min = new Vector2(Mathf.Infinity, Mathf.Infinity);
            var max = -min;
            foreach (var c in cols)
            {
                var minmax = NavMeshUtils2D.AdjustMinMax(c, min, max);
                min = minmax[0];
                max = minmax[1];
            }

            // create ground (cube instead of plane because it has unit size)
            // (pos between min and max; scaled to fit min and max * scale)
            // note: scale.y=0 so that *navmeshExtends doesn't make it too high
            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go.name = "Ground"; // for debugging
            go.isStatic = true;
            go.transform.parent = obj.transform;
            float w = max.x - min.x;
            float h = max.y - min.y;
            go.transform.position = new Vector3(min.x + w/2, -0.5f, min.y + h/2);
            go.transform.localScale = new Vector3(w, 0, h) * navmeshExtends;
        }


        // bake navmesh asynchronously, clear mesh
        UnityEditor.AI.NavMeshBuilder.BuildNavMeshAsync(); // Async causes weird results
        if (gizmesh != null) gizmesh.Clear();
        needsRebuild = true; // rebuild as soon as async baking is finished

        // delete the gameobjects now that the path was created
        GameObject.DestroyImmediate(obj);
    }

    // editor window ///////////////////////////////////////////////////////////
    [MenuItem("Window/Navigation2D")]
    public static void ShowWindow()
    {
        // Show existing window instance. If one doesn't exist, make one.
        EditorWindow.GetWindow(typeof(Navigation2D));
    }

    static Texture2D logo
    {
        get
        {
            return (Texture2D)EditorGUIUtility.Load("Assets/Navigation2D/logo.png");
        }
    }

    void OnGUI()
    {
        GUILayout.BeginVertical();

        // colored logo
        //var backup = GUI.backgroundColor;
        //GUI.backgroundColor = Color.white;
        //GUILayout.BeginVertical("box");
        GUILayout.Label(logo, new GUIStyle(GUI.skin.label){alignment=TextAnchor.MiddleCenter});
        //GUILayout.EndVertical();
        //GUI.backgroundColor = backup;
        GUILayout.Label("<b>by noobtuts.com</b>", new GUIStyle(GUI.skin.label){richText=true,alignment=TextAnchor.MiddleCenter});

        // instructions
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Instructions", EditorStyles.boldLabel);
        EditorGUILayout.HelpBox(@"1. Make your 2D Colliders Static
2. Press Bake and wait until it's done
3. Add NavMeshAgent2D to agents", MessageType.Info);
        EditorGUILayout.Space();

        // get access to original navigation settings
        // (that's how Unity's Navigation window does it too)
        var settings = new SerializedObject(UnityEditor.AI.NavMeshBuilder.navMeshSettingsObject);
        SerializedProperty agentRadius = settings.FindProperty("m_BuildSettings.agentRadius");
        SerializedProperty agentHeight = settings.FindProperty("m_BuildSettings.agentHeight");

        // settings header
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Settings", EditorStyles.boldLabel);

        // diagram
        Rect controlRect = EditorGUILayout.GetControlRect(false, 120f, new GUILayoutOption[0]);
        NavMeshEditorHelpers.DrawAgentDiagram(controlRect, agentRadius.floatValue, agentHeight.floatValue, 0, 0);

        // agent radius
        agentRadius.floatValue = EditorGUILayout.FloatField(new GUIContent("Agent Radius", "Modifies the built in Agent Radius from Window->Navigation"), agentRadius.floatValue);
        settings.ApplyModifiedProperties();

        // ground extends
        navmeshExtends = EditorGUILayout.Slider(new GUIContent("NavMesh Extends", "Can be used to cover the outside of your scene with a NavMesh"), navmeshExtends, 1, 100);

        // visibility
        drawMode = EditorGUILayout.IntPopup("Mode", drawMode, new string[]{"Wireframe", "Full"}, new int[]{0, 1, 2});

        // repaint scene if drawMode option changed
        if (GUI.changed)
            SceneView.RepaintAll();

        // buttons
        EditorGUILayout.Space();
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Clear", GUILayout.Width(95f)))
        {
            UnityEditor.AI.NavMeshBuilder.ClearAllNavMeshes();
            if (gizmesh != null) gizmesh.Clear();
        }
        if (UnityEditor.AI.NavMeshBuilder.isRunning)
        {
            if (GUILayout.Button("Cancel", GUILayout.Width(95f))) UnityEditor.AI.NavMeshBuilder.Cancel();
        }
        else
        {
            if (GUILayout.Button("Bake", GUILayout.Width(95f))) BakeNavMesh2D();
        }
        GUILayout.EndHorizontal();

        GUILayout.EndVertical();
    }

    // save & load editor settings /////////////////////////////////////////////
    void LoadSettings()
    {
        if (EditorPrefs.HasKey("Navigation2D_navmeshExtends"))
            navmeshExtends = EditorPrefs.GetFloat("Navigation2D_navmeshExtends");

        if (EditorPrefs.HasKey("Navigation2D_drawMode"))
            drawMode = EditorPrefs.GetInt("Navigation2D_drawMode");
    }

    void SaveSettings()
    {
        EditorPrefs.SetFloat("Navigation2D_navmeshExtends", navmeshExtends);
        EditorPrefs.SetInt("Navigation2D_drawMode", drawMode);
    }

    void OnFocus()
    {
        LoadSettings();
    }

    void OnLostFocus()
    {
        SaveSettings();
    }

    void OnDestroy()
    {
        SaveSettings();
    }

    // visibility //////////////////////////////////////////////////////////////
    // simple helper to find out if the window is currently visible or not
    static bool visible = false;

    public void OnBecameVisible()
    {
        // repaint scene view to refresh gizmo when we show the window
        // otherwise it's only refreshed when clicking into the scene view again
        SceneView.RepaintAll();
        visible = true;
    }

    public void OnBecameInvisible()
    {
        // repaint scene view to refresh gizmo when we hide the window
        // otherwise it's only refreshed when clicking into the scene view again
        SceneView.RepaintAll();
        visible = false;
    }

    // gizmo ///////////////////////////////////////////////////////////////////
    static bool needsRebuild = false;
    static Mesh gizmesh;
    static void RebuildGizmesh(NavMeshTriangulation nm)
    {
        // the mesh is cleared after stopping the game, rebuild if necessary
        if (!gizmesh) gizmesh = new Mesh();
        gizmesh.vertices = nm.vertices.Select(v => new Vector3(v.x, v.z, 0)).ToArray(); // TODO utils?
        gizmesh.triangles = nm.indices;
        gizmesh.normals = gizmesh.vertices.Select(_ => new Vector3(0, 0, -1)).ToArray();
        needsRebuild = false;
    }

    [DrawGizmo(GizmoType.Selected | GizmoType.NonSelected)]
    static void OnGizmo(Transform tf, GizmoType gt)
    {
        // only show navmesh while the window is visible
        // Gizmos.Draw is slow, so only do it when the user really needs it.
        // otherwise bigger games would be slow all the time.
        if (!visible) return;

        // rebuild if necessary
        if (!gizmesh || needsRebuild)
            if (!UnityEditor.AI.NavMeshBuilder.isRunning)
                RebuildGizmesh(NavMesh.CalculateTriangulation());

        // draw if not empty
        if (gizmesh.vertices.Length > 0)
        {
            Gizmos.color = Color.cyan;
            if (drawMode == 0)
            {
                Gizmos.DrawWireMesh(gizmesh);
            }
            else if (drawMode == 1)
            {
                Gizmos.DrawMesh(gizmesh);
                Gizmos.DrawWireMesh(gizmesh);
            }
        }
    }
}
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por NKKF Qui Out 04, 2018 6:48 pm

Acho que é melhor você pedir suporte ao dono do Asset pago.
NKKF
NKKF
ProgramadorMaster

Masculino PONTOS : 4570
REPUTAÇÃO : 574
Idade : 19
Áreas de atuação : Desenvolvedor na Unity, NodeJS, React, ReactJS, React Native, MongoDB e Firebase.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh Aad8pUi

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Qui Out 04, 2018 7:02 pm

Ai é que ta o problema. Paguei e ele disse que agora não tinha tempo para dar suporte. Afffff.
Então tive que buscar recursos. Se alguém puder ajudar. Sou iniciante ainda em C#.
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por dstaroski Qui Out 04, 2018 8:05 pm

Nowsfeky escreveu:Ai é que ta o problema. Paguei e ele disse que agora não tinha tempo para dar suporte. Afffff.
Então tive que buscar recursos. Se alguém puder ajudar. Sou iniciante ainda em C#.
Boa noite cara! olha, é complexo demais os códigos para interpretar sem estar com o Asset completo em cena. Porém, se você comprou, o desenvolvedor é OBRIGADO a te dar o suporte, caso contrário, você poderá denuncia-lo se reportando também ao suporte da Unity a respeito da falta de suporte do desenvolvedor.

Abraço!
dstaroski
dstaroski
Instrutor

Masculino PONTOS : 6052
REPUTAÇÃO : 1123
Idade : 34
Áreas de atuação : Teologia, Unity 3D, C#, HTML, CSS, Dart, Flutter.

Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh Aad8pUi

http://diegodeoliveira.gamejolt.io/defeattheilluminatis

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Sex Out 05, 2018 9:12 am

Bom dia dstaroski ! Pedi ajuda a ele e a única coisa que ele falou para eu fazer foi o seguinte:

Modify your player's movement script to always set agent.destination = (1,1) or (2,3) etc


Mas não entendi muito bem o que fazer. Vc ou alguem poderia me ajudar?
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por dstaroski Sex Out 05, 2018 10:29 am

Nowsfeky escreveu:Bom dia dstaroski ! Pedi ajuda a ele e a única coisa que ele falou para eu fazer foi o seguinte:

Modify your player's movement script to always set agent.destination = (1,1) or (2,3) etc


Mas não entendi muito bem o que fazer. Vc ou alguem poderia me ajudar?
putz cara, também não entendi direito, tenta por esses valores como distancia de parada do destino para ver se ajuda.

Abraço!
dstaroski
dstaroski
Instrutor

Masculino PONTOS : 6052
REPUTAÇÃO : 1123
Idade : 34
Áreas de atuação : Teologia, Unity 3D, C#, HTML, CSS, Dart, Flutter.

Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh Aad8pUi

http://diegodeoliveira.gamejolt.io/defeattheilluminatis

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Sex Out 05, 2018 10:40 am

Se eu colocar esses valores em destino, ai não importa onde eu clico no mapa, o player sempre vai para essa mesma coordenada. Pelo que eu entendi não preciso mexer na lógica do asset  e sim apenas no script do player. Pois o asset dele apenas converte o recurso Navigation 3D do Unity para 2D.

Pois o movimento pelo teclado é até simples e usado pela maioria mas quero que o player pare sempre no meio do tile, ou seja, quando aperto e solto a seta quero que ele saia do meio do tile e pare exatamente no meio do outro.
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por dstaroski Sex Out 05, 2018 11:20 am

Nowsfeky escreveu:Se eu colocar esses valores em destino, ai não importa onde eu clico no mapa, o player sempre vai para essa mesma coordenada. Pelo que eu entendi não preciso mexer na lógica do asset  e sim apenas no script do player. Pois o asset dele apenas converte o recurso Navigation 3D do Unity para 2D.

Pois o movimento pelo teclado é até simples e usado pela maioria mas quero que o player pare sempre no meio do tile, ou seja, quando aperto e solto a seta quero que ele saia do meio do tile e pare exatamente no meio do outro.
entendi, bom cara, eu já não tenho mais como te ajudar, ainda mais que é um código complexo e tals, acho que você deve ir testando e pesquisando a respeito do Asset, e enche o saco do desenvolvedor também para te auxiliar.

Abraço!
dstaroski
dstaroski
Instrutor

Masculino PONTOS : 6052
REPUTAÇÃO : 1123
Idade : 34
Áreas de atuação : Teologia, Unity 3D, C#, HTML, CSS, Dart, Flutter.

Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh Aad8pUi

http://diegodeoliveira.gamejolt.io/defeattheilluminatis

Ir para o topo Ir para baixo

PEDIDO Re: Ajuda com script movimento por Grid Tile no Navmesh

Mensagem por Nowsfeky Sex Out 05, 2018 11:27 am

OK. Vlw.
Nowsfeky
Nowsfeky
Iniciante
Iniciante

Masculino PONTOS : 2065
REPUTAÇÃO : 5
Idade : 37
Áreas de atuação : Iniciante em programação C#.
Respeito as regras : Ajuda com script movimento por Grid Tile no Navmesh WvDYdlf

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos