Search code examples
javascriptthree.jsspriteperspectivecamera

Initial Sprite Size in Three.js


Can someone help me understand how three.js initially determines the size/scale of a sprite?

At the moment I'm working with 4 sprites (PNGs with transparency that are 3000px × 1830px) stacked in 3D space, but I'm having to scale them up between 16x and 22x. In order to keep the sprites from looking squashed, though, I have to scale the y-axis 75% of the x-scale.

Eventually, I want to be able to pull in images systematically, and have them scale appropriately.

It's possible I just haven't set this thing up correctly. It looks right, but it's super hacky-feeling right now. I pretty much changed a bunch of numbers, until it looked right to me. I don't like that. I want to understand.

Here's what I'm working with currently: http://valorink.com/3d-test/stackoverflow/


Solution

  • Looking into the code of the Sprite class reveals that a simple plane with width and height of 1 is created in the constructor. I wouldn't have expected anything else, because the geometry size is usually not defined by the texture size.

    You probably want them to fill the viewport, so you have to scale them. With perspective camera its a bit of math, because the amount of x-scale (or y-scale) to fit the viewport size relates to the distance to the camera. So, it should be something like

    var halfHeigt = distanceToCamera / Math.tan( camera.fov/2 * Math.PI / 180 );
    y-scale = halfHeight * 2;
    

    And of course you need to consider the aspect ratio in order to not looking squashed. So, x-scale should be y-scale * textureWidth / textureHeight, or the other way round y-scale = x-scale * textureHeight / textureWidth.