Dynamically created mesh being on the wrong position after movement

I’m trying to create a field of view for my character in a 2D game. I used the tutorial created from the youtuber Code Monkey. The problem is, the field of view is created correctly, but when I move the gameobject that the mesh is attached, the mesh moves faster, for no reason apparently. I removed the field of fiew generation, and just put a simple square to test the movement, to check if the problem was on my code, but it seems it wasn’t. The square mesh is created on the gameobject position and after the movement, it should be on the same place as the gameobject, but is moving faster than the gameobject.

Image of the problem:

using UnityEngine;

public class FieldOfView : MonoBehaviour {
    private Mesh _mesh;
    private Vector2 _origin;

    private void Start() {
        _mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = _mesh;
        _origin = transform.position;

        MeshTest();
    }

    private void Update() {
        Vector2 movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * Time.deltaTime * 3;

        if (movement == Vector2.zero) return;

        transform.position = transform.position + (Vector3)movement;
        _origin = transform.position;

        MeshTest();
    }

    private void MeshTest() {
        Vector3[] vertices = new Vector3[4];
        Vector2[] uv = new Vector2[vertices.Length];
        int[] triangles = new int[6];

        vertices[0] = _origin + new Vector2(-0.5f, -0.5f);
        vertices[1] = _origin + new Vector2(-0.5f, 0.5f);
        vertices[2] = _origin + new Vector2(0.5f, 0.5f);
        vertices[3] = _origin + new Vector2(0.5f, -0.5f);

        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 3;
        triangles[3] = 1;
        triangles[4] = 2;
        triangles[5] = 3;

        _mesh.vertices = vertices;
        _mesh.uv = uv;
        _mesh.triangles = triangles;
    }
}

I just discovered that the mesh is now configured to be positioned locally on the gameobject, I just removed the gameobject position from the vertices and it worked fine. So simple :roll_eyes:

1 Like