Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question ¿Cómo pinto los vértices de la malla teniendo en cuenta la posición del jugador?

Discussion in 'World Building' started by Iarix_wolf, May 1, 2024.

  1. Iarix_wolf

    Iarix_wolf

    Joined:
    Jun 23, 2022
    Posts:
    1
    Hola, estoy tratando de hacer una nube que cambie a opacidad 0 cuando el jugador pace por encima. Esta es para un juego 2D y la idea es que se use en el mapa. Comencé con un plano con varias subdivisiones y hago que los vertices cambien a rojo (Solo para probar que funcione).

    Tengo este código:

    using UnityEngine;

    [RequireComponent(typeof(MeshFilter))]
    public class MapCloud : MonoBehaviour
    {
    Mesh mesh = null;
    Vector3[] vertices;
    Color[] colors;

    public Transform player;
    public float brushSize = 1;
    Vector3 posPlayer;

    void Awake()
    {
    mesh = GetComponent<MeshFilter>().mesh;
    }

    void Update()
    {
    if (posPlayer != player.position)
    {
    UpdateVertexColors(player);
    posPlayer = player.position;
    Debug.Log(posPlayer);
    }

    }

    void UpdateVertexColors(Transform player)
    {
    var vertices = mesh.vertices;
    var colors = new Color[vertices.Length];

    float closestDistanceSqr = Mathf.Infinity;
    int closestVertexIndex = -1;

    // Transform player position to mesh local space if needed
    Vector3 playerPosition = transform.InverseTransformPoint(player.position);

    // Find the closest vertex
    for (int i = 0; i < vertices.Length; i++)
    {
    float distSqr = (vertices - playerPosition).sqrMagnitude;
    if (distSqr < closestDistanceSqr)
    {
    closestDistanceSqr = distSqr;
    closestVertexIndex = i;
    }
    }

    // Color the closest vertex red
    for (int i = 0; i < colors.Length; i++)
    {
    if (i == closestVertexIndex)
    {
    if (colors == Color.red)
    colors = colors;
    else
    colors = Color.red;
    }
    }

    mesh.colors = colors; // Apply the new color array to the mesh
    }
    Así se ve en Unity: upload_2024-5-1_17-13-53.png upload_2024-5-1_17-17-8.png

    No estoy logrando que el rojo se quede al mover al jugador. Y tampoco que no solo me agarre el vértice más cercano, sino también sus vecinos o más dependiendo de un valor numérico que yo le agregue:

    Si alguien tiene una solución, les estaría muy agradecida porque es algo que me está costando lograr.

    Un saludo, gracias.