Search code examples
pythonursina

How to add texture to mesh entity


I had created a simple entity with the mesh model, and i'd like to add texture on it.

Here is the code:

class Slide(Entity):
    def __init__(self, position = (0, 0, 0), rotation = (0, 0, 0)):
        super().__init__(
            model = Mesh(vertices = ((-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5), (0.5, -0.5, 0.5), (0.5, -0.5, -0.5), (-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5)), triangles = (0, 4, 3, 0, 5, 4, 0, 1, 5, 1, 2, 5, 0, 3, 1, 1, 3, 2, 4, 5, 2, 3, 4, 2)),
            color = color.gray,
            position = position,
            rotation = rotation,
            texture = 'white_cube'
        )

slide = Slide()

The object created then will be like this:

enter image description here

The problem is: I had tried adding some default textures onto it, but the only result i receive is a darker color of the original.

How can i fix this? Thanks.


Solution

  • You have to provide a list of uvs, where you map each vertex (Vec3) to a texture coordinate (Vec2). The reason you only get a darker version when setting a texture is that it only use the first pixel in the texture since it doesn't know how to map it.

    For example, a quad consisting of two triangles can be mapped like this:

    Mesh(
        vertices=((0.5, 0.5, 0), (-0.5, 0.5, 0), (-0.5, -0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (-0.5, -0.5, 0)), 
        uvs=((1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (0, 0))
    )
    

    Creating a complex uv map through code can be difficult, so you should use a 3d modeling program for that. However, if it's something simple like project from one side, you could use the vertex coordinates to generate the uvs. Something like ...

    uvs = [(v[0], v[1]) for v in vertices]
    

    ... if you want to project from the front for example.