Version: 2019.1
Practical guide to optimization for mobiles
Приёмы в коде и игровом процессе

Графические приёмы

На что способны мобильные устройства? Как нужно планировать свою игру? Если игра тормозит, и профайлер показывает что проблема в рендеринге, как узнать что именно нужно изменить? Как сделать так, чтобы ваша игра выглядела лучше и оставалась быстрой? Эта страница посвящена общему, не техническому изложению методов. Если вы ищете что-то специфическое, см. Оптимизации визуализации.

Что можно реализовывать на текущих пользовательских устройствах:

  • Lightmapped static geometry. But beware of:
    • Using a lot of alpha-test shaders
    • Bumpmapping, especially using built-in shaders.
    • High polygon count
  • Animated characters, even with fancy shaders! But beware of:
    • Massive crowds or high-poly characters
  • 2D games with sprites. But beware of:
    • Overdraw, or, lots of layers drawn on top of each other.
  • Particle effects. But beware of:
    • High density on large particles. (Lots of particles drawn on top of each other. This is another overdraw situation)
    • Ridiculous numbers of particles, or particle colliders.
  • Physics. But beware of:
    • Mesh colliders.
    • Lots of active bodies.

Что НЕ НУЖНО реализовывать на текущих пользовательских устройствах:

  • Графические эффекты в полном экране (такие как свечение и глубина резкости).
  • Dynamic per-pixel lighting (multiple lights marked Important and not baked into the lightmap)
    • Every affected object is drawn an additional time for every dynamic light you use, and this gets slow quickly.
  • Real time shadows on everything
    • Unity has support for real time shadows on mobile platforms, but their use must be very judicious, and likely limited to higher-end devices.

Примеры - как сделаны первоклассные мобильные игры

Shadowgun

Shadowgun - замечательный пример того, что может быть сделано на текущем мобильном программном обеспечении. Более конкретно, это хороший пример того, что не следует делать и как обойти ограничения. Тем более что небольшую часть игры сделали общедоступной здесь сообщение в блоге.

Вот основные вещи, которые реализует Shadowgun для сохранения производительности:

  • Dynamic lighting - barely used.
    • Blob shadows and Lightmaps are used instead of any real shadows.
    • Lightprobes, instead of real lights, are used on their characters.
      • Muzzle flashes added into the lightprobe data via script.
    • The only dynamic per-pixel lighting is an arbitrary light direction used to calculate a BRDF on the characters.
  • Bumpmapping - barely used.
    • Real bumpmapping only used on characters.
    • As much contrast and detail as possible is baked into the diffuse texture maps. Lighting information from bumpmaps is baked in.
    • A good example is their statue texture, or their shiny wall, as seen on the right. No bumpmaps are used to render these, the specularity is faked by baking it into the texture. Lightmapping is combined with a vertex-lighting-based specular highlight to give these models a shiny look.
    • If you want to learn how to create textures like this one, check out the Rendering Optimizations page.
  • Dense particles - avoided.
    • UV-scrolling textures used instead of dense particle effects.
  • Fog effects - avoided.
    • Their god rays are hand-modeled.
    • Single planes that fade in and out are used to achieve cinematic fog effects without actually rendering any fog.
      • This is faster because the planes are few and far between, and it means that fog doesn’t have to be calculated on every pixel and in every shader.
  • Glow - avoided.
    • Blended sprite planes are used to give the appearance of a glow on certain objects.

Sky Castle Demo

This demo was designed to show what Unity is capable of on high-end Android devices.

  • Dynamic lighting - not used.
    • Lightmaps only.
  • Bumpmapping - used
    • The bricks are all bumpmapped, lit by directional lightmaps. This is where the “high-end devices” part comes into play.
  • Real time reflections - limited.
    • They carefully placed their real-time reflecting surfaces separately and in isolated areas, so that only one runs at a time, and the environment that needs to be rendered twice can be easily culled.

Итог - Что это означает для вашей игры

Чем больше вы будете уделять внимания и лучше понимать ограничения мобильных устройств, тем лучше будет выглядеть ваша игра, и тем лучше будет производительность. Если вы хотите сделать игру высокого класса для мобильных, вы извлечете немалую пользу от понимания того, как строится графика в Unity и будете способны написать свои шейдеры. Если же вы хотите использовать уже готовые шейдеры из ShadowGun, они доступны здесь.

Не имитируйте! Запекайте!

Нет сомнений что игры пытаются следовать законам природы. Движение параболического снаряда и цвет каждого блестящего пикселя написанным по формулам, имитирующим наблюдения в реальном мире. Но научная симуляция - только одна часть игры, есть еще другая - рисование. На мобильном маркете вы не сможете конкурировать с физически точно воссозданной визуализацией; аппаратная часть не позволяет этого сделать. Если вы слишком увлечетесь в имитации реального мира, ваша игра может быть неограниченной, серой и залагованной.

Рисуйте свои полигоны и смешивайте краски как художник.

Запекание карт рельефа в Shadowgun отличный пример этого. Зеркальное освещение там уже в текстуре, человеческий глаз не замечает того, что они на самом деле не совпадают с направлением света, по текстуре это просто контрастные детали, полностью сфальсифицированные, но, в конечном итоге выглядящие превосходно. Это распространенные “обманки”, которые используются во многих успешных играх. Сравните шлем в первый скриншот из Halo, до релиза с этим шлемом релизный скриншот. Создается видимость того, что выступы брони отражаются в шлеме, но на самом деле это отражение запечено в текстуру шлема. В Лиге Легенд (League of Legends), есть небольшой эффект, создающий видимость пиксельного освещения, но на самом деле там смешанная плоскость с текстурой, которая возможно создана в момент записи снимка экрана, пиксельный свет, сияющий на земле.

Что хорошо работает:

  • Lightmapped static geometry
    • Dramatic lighting and largely dynamic environments don’t mix. Pick one or the other.
  • Lightprobes for moving objects
    • Current mobile hardware is not really cut out for lots of dynamic lights, and it can’t do shadows. Lightprobes are a really neat solution for complex game worlds with static lighting.
  • Specialized shaders and detailed, high-contrast textures
    • The shaders in ShadowGun minimize per-pixel calculations and exploit complex and high-quality textures. See the Rendering Optimizations page for information on how to make textures that look great even when the shader is simple.
  • Cartoon Graphics
    • Who says your game has to look like a photo? If you make lighting and atmosphere the responsibility of the texture artist, not the engine, you hardly even have to worry about optimizing rendering.

What does not work:

  • Glow and other Post processing effects
    • Approximate such effects when possible by using blended quads, check out the Shadowgun project for an example of this.
  • Bumpmapping, especially with the built-in shaders
    • Use it sparingly, only on the most important characters or objects. Anything that can take up the whole screen probably shouldn’t be bumpmapped.
    • Instead of using bump maps, bake more detail and contrast into the diffuse texture. The effect from League of Legends is an interesting example of this being used successfully in the industry.

Но как я смогу это сделать?

См. Оптимизации рендеринга

Practical guide to optimization for mobiles
Приёмы в коде и игровом процессе