I have an object with a pattern of blue stripes, as well as red stoplights. I need to make a separate material for each drawing in order to make the "ripple" animation in the future. But when two or more materials are superimposed, one overlaps the other (materials with patterns and base material). Is there any way I can make them not overlap each other?
Related
Part 1: Forgive me if the question itself is unclear. I am learning how to use Unity and script in C#, and I want to know if there's a way to apply a gradient of color (or an image) utilizing the game objects that already exist as the places where the gradient will show up.
Say I have a group of these circles that randomly grow and change size during the game run.
Example image of circles
I am not sure of the correct terminology, but a couple of words come to mind, i.e. shader/mask. My goal is to display the gradient/image only within where the game objects exist. So instead of white circles, it's circles display parts of the one singular image/gradient.
Part 2:
To take a it a step further, I'd like to know how to have the gradient continuously run through its spectrum so one can see the colors shift across the circles.
Again, still very new to this kind of stuff, but would anyone know what steps I would need to take to get there.
Thanks!
I'm having some issues with items of clothing on an avatar as you can see in the image below
Most would suggest that i simply pull the trousers away from the body within the modelling software which is fine until it is combined with other items of clothing
I could now pull the shirt away from the trousers but I have many different items of clothing and to check/adjust each of them does not seem like the way to go.
It would be better to try and apply some sort of layering system.
Can anyone advise me on how i may be able to achieve such a system or a how i can achieve the results I am aiming for?
I have already looked into trying to do this using shaders but had no luck achieving the result I'm trying to get (but admittedly I am no Shaderlab/CG expert)
I have also tried separating the avatar into different pieces and replacing them with the clothing meshes but this still leaves the problem of the clothing being visible through each other.
I would like to preferably have some sort of system where i can layer each item of clothing so that no matter what they display on top of each other in the correct order without any overlaps.
If you really want to use layering you can use Unity's Render Layers which are actually made for that.
Go to Layers -> Edit Layers
Add the Layers you want (the order doesn't matter)
Asign the Layers to the objects you want to be rendered by a ceratin camera.
as an example I added a trousers cube with layer trousers, a pillover cube with layer pullover and a OnTop cube with layer OnTop
Create a new Empty GameObject and call it e.g. CameraParent. This will contain all your cameras and you should move this one instead of the camera you moved so far.
In case this is a VR/AR app you might have to attach a Camera component to this parent object, make it the main camera but make it not render anything
Create e.g. 4 Child objects and give them a Camera component. Also make sure only one Camera is tagged as MainCamera and only one has an AudioListener in your Scene. I used 4 cameras as example to have a TrousersCamera a PulloverCamera an OnTopCamera and a BackgroundCamera.
Now the setup for the rendering
BackgroundCamera
Here you render anything else like you did before
ClearFlags: e.g. SkyBox
Culling Mask: select all Layers except trousers, pullover and OnTop
Depth: -1
TrousersCamera
For rendering the trousers (on top of anything else)
ClearFlags: Depth only
Culling Mask: select only trousers
Depth: 0 (you see a bigger value is rendered on top of a lower value)
PulloverCamera
For rendering the pullover on top of the trousers
ClearFlags: Depth only
Culling Mask: select only pullover
Depth: 1
OnTopCamera
For rendering something else on top of everything
ClearFlags: Depth only
Culling Mask: select only OnTop
Depth: 2
As result you can see that though the red cube (OnTop cube) is really far behind the rest and the blue cube (Pullover cube) in the middle, the red one will allways be rendered on top, than the blue, than the brown (trousers cube) and finally the background.
Since my day one in Unity development, I've seen tips and stuff saying that we should never tint sprites. If we want sprites of different colors, create them and place them in the same texture, and then swap in the differently-colored sprites.
The reasoning is that tinting sprites will break batching.
I have created a small demo.
Situation 1
The same square sprite is used in 6 game objects. No surprise here. In the stats, there is 1 batch. 5 are saved by batching.
Situation 2
The same square sprite is used in 6 game objects again, but this time, all of them are tinted red with the same color value.
Shouldn't this be breaking batching already?
Situation 3
For the sake of completeness, I tinted the square sprites with different colors. Still, we have 1 batch and 5 saved. Nothing's changed.
Additional information
I captured Situation 1 & 2 during a single play through, and situation 3 in a separate play through.
I tried tinting the sprites directly in the editor by changing the "Color" field of SpriteRenderer and through scripts by changing SpriteRenderer.color. The results are the same.
Changing color of sprites on the SpriteRenderer component shouldn't break batching. What breaks batching is when you change the SpriteRenderer's sprite, the material or even when you try to access the material with SpriteRenderer.material property.
For example,
This breaks batching:
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.material.color = Color.red;
because you are accessing the material. It will create new material instance when you access the material property for the first time.
This will not break batching:
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.color = Color.red;
It will not because it is not accessing the material property. Even though it will not break batching, one issue with it is performance. It affects performance when you do this.
AFAIK, tinting is basically setting a vertex color. This is done for particles, where you can set random start colors and all the particles are rendered in a single draw call. Vertex color does not change/create a new material.
Not sure how that was handled in early Unity versions, but sprites should be simple quads and therefore support vertex colors. The Sprite shader probably works the same way in terms of tinting.
In general, you are right. Changing shader properties will create a duplicate of that material, or it will change the material itself and affect all instances using the material. Did you use the tint on the sprite material, or on the spriteRenderer?
By hand, I could think of using MaterialPropertyBlocks, but maybe Unity did exactly that for sprites.
Some more Detail to clarify:
A You have "Material01.mat" - it's green. You copy this material to 10 sprites. You want to have 10 colors? You have to create 10 materials, each holding the desired color - 10 Draw calls.
You can do the same by script, just change material.color. But Unity will duplicate the materials for you. Still 10 Draw calls. Some people are confused why it breaks batching until they hear about this.
B You changed the RENDERERs tint. This Sprite Renderer will write the tint color into your sprites vertices (probably 4?) - using the vertex color attribute. It's basically free, because they are transmitted to the gpu anyway (afaik)
As I said above, the same is used in the Particle System, to allow rainbow particles with 1 Drawcall.
So, any particle Shader, self-written shader, or Sprite Shader should work with this. All you need is a.albedo = c.rgb * IN.vert.color (a bit pseudo code here)
That means, the same shader, and the same material can be used for multiple objects, having different vertex colors. That won't break batching.
You can even have different objects of any shape and vertex count, giving them different vertex colors (per vertex, like gradients etc) and it will still batch.
Check Static whenever possible, feed information into vertex colors, and for moving objects, try to keep them under 300 verts, so dynamic batching can work.
But for Sprites, unity automated this for you, you simply need to use the SpriteRenderer - that's why you don't use a quad with a texture, but a "Sprite" and a SpriteRenderer.
Again, I could be wrong and the SpriteRenderer actually uses MaterialPropertyBlocks, but it works almost the same. These variables can be set per object and do not create new DrawCalls. The variable values are used in the shader, so the material/shader is the same for multiple objects.
I'm totally new in game-dev and would like to know the best practice about above question.
Let me explain more.
I want to create 2D game with top-down view and with free movement (without snapping to the grid) just like any Zelda game on GameBoy.
How should I store map bounds? Is there a way to do this automatically? For example I have a texture with background and texture with foreground where black color should appear transparent and should allow to move in space of it.
Thanks in advance.
For easy 2D collision detection, you'll probably implement bounding boxes.
Basically you will create a rectangle that represents every Game Object. The coordinates and size of the rectangle will be the same as the Texture2D (it is common to make this a property on the given class). Every time you update the position of your Texture, you update the position of your bounding box.
Now to check for collision, just loop through your game objects and see if any of the bounding boxes intersect.
Once you get the idea, you'll see that its very easy to implement. XNA also provides some math helpers to abstract the math (though its simple addition and subtraction).
Try this link for a more in depth explanation with code examples: http://www.dreamincode.net/forums/topic/180069-xna-2d-bounding-box-collision-detection/
I want to create polarized 3D image using Matlab or C#?.
Is any way to create 3D image from any 2D image using Matlab or C#?
Polarized 3D is an effect created in the physical world with physical projectors shining onto the same spot of a physical screen. It's not a digital effect that you can create in an image on a computer screen. You cannot write code to render an image onto a normal computer screen then see 3D with the polarized glasses.
Stereoscopic images for use with polarised glasses are created by projecting the left and right eye images so that they overlap through separate projectors which have a polarising filter fitted.
The same is true for the red and green tinted glasses (which are not the same as the old style anaglyph images).
If you only have one 2D image you cannot create a 3D image from it without getting involved in manual image processing.
Build your own Polarized Stereoscopic Projection System
Principles of Polarization Optics
Polarized Light
Since the late 19th century we know, that light can be described in terms
of electromagnetic waves. The theory behind it are the well understood
Maxwell Equations. Since this is not an article about electrodynamics just
the essentials:
Light is electromagnetic radiation with wavelenghts between 800nm (red) to 400nm (violet).
Electromagnetic radiation has an electric and a magnetic field component.
The electric and magnetic field are transversal, which means perpendicular to the propagation of the wave.
The electric and magnetic field are perpendicular to each other.
http://en.wikipedia.org/wiki/Electromagnetic_radiation
The electric field vector (one could also use the magnetic field, but convention
is to use the electric filed) determines the polaization. There are two kinds of
polarization:
Linear polarization: The electric component remains in one single plane, the polarization plane
Circular polarization: With each cycle the electric component "swings" into different direction
If you look along the propagation the field vector may cycle through:
↑→↓← -- this is called right turning polarization
↑←↓→ -- this is called left turning polarization
The effect of circular polarization is created by retarding one component
of linear polarized light by a quarter of a wavelength.
See also this Wikipedia article
http://en.wikipedia.org/wiki/Polarization_(waves)
Creating Polarized Light
Wikipedia has an excellent article on the details
http://en.wikipedia.org/wiki/Polarizer
Here's the essentials.
Linear Polarization
Linear polarized light can be obtained in various ways:
By filtering out all unwanted polarization components
from light with a broad polarization distribution.
All light emitted in a statistical manner (thermic radiation,
high pressure gas discharge, lighting arcs) has this property.
One can filter the desired polarization plane using a filter.
The following filters are known:
Brewster Beam Spliters use brewster reflection to split
a beam of light into two polarization components, polarized
perpendicular to each other.
Birefringence employs the phenomenon that some crystals
have different indices of refraction for different polarization
planes. Again the light ways are split.
Absorption in strechted polymers. Stretching a polymer gives
it an anisotropic structure. Some anisotropic polymers will absorb
only incoming light polarized parallel (or perpendicular, it
depends on the material) to the strechting direction.
The light emited from a laser is linear polarzied.
Depending on how the laser is built, the polarization plane will
gradually change over time.
http://en.wikipedia.org/wiki/Linear_polarization
Circular Polarization
In optics, circular polarization is created by passing linear polarized
light through some anisotropic material, that will retard one of the
components (electric or magnetic) by a quarter of the wavelength. This
is called a λ/4 retarder.
The angle between linear polarization and the anisotropic material's major
axis determines ratio between left and right turning polarized light resulting:
Incoming linear polarized light tilted by +45° will be fully left turning.
Incoming linear polarized light tilted by -45° will be fully right turning.
Incoming linear polarized light tilted by 0° will consist of 50% left and 50% right turning.
It should be noted, that due to the reversibility of the light's way the
passing of circular polarized light through a λ/4 retarder will
turn it into linear polarized light of the corresponding certain polarization
plane. This linear polarized light can the be filtered again by linear
polarizers. This is, how circular polarization 3D glasses work.
http://en.wikipedia.org/wiki/Circular_polarization
Polarized Light and Interaction with the Screen
Scattering and Diffraction
The typical projection screen uses very small particles, usually they're TiO2,
to scatter and diffract the light into all directions. In the scattering process
the light bounces multiple times between the particles. While each bounce leaves
a light wave solition polarized in the grand statistical scheme any notable
polarization is lost.
Thus a normal white projection screen is unsuitable for polarized stereoscopic projection.
Metallic Reflection
The key for building a polarizing stereoscopic projection system is the use
of a screen material that retains the polaization of the incoming light.
This is achieved by employing metallic reflection on particles much larger than
the light's wavelengths.
A DIY Stereoscopic Projection System
Making a DIY Silver Screen
You'll need:
aluminum powder pigment
clear acrylic base
deep black textile dye
canvas
This is how you do it:
Dye the canvas deep black. This will absorb any light not reflected,
instead of scattering it. Let it dry thorougly. You may repeat step 1
multiple times.
Paint one layer of clear acrylic base on the now deep black dyed canvas.
Doing it one side suffices. All futher steps are now done on this clear acrylic base.
Make a very thick aluminum acrylic paint. Here are a few hints:
Mix the aluminum powder with the acrylic base in very small batches.
Don't make a aluminum power paste by mixing it with water!
After putting each small batch of aluminum powder into the acrylic
stir thoroughly so that it is a homogenous mass.
You should end up with a 1 part aluminum powder to 1 part acrylic base paint
Once you've got that thick paint, thin it with 1 part of water.
Apply layers of aluminum acrylic paint on the prepared canvas. Let each layer dry.
Repeat step 4 until you've got an even aluminum metallic painted surface with no
black parts shining through.
Video Projection
Single Projector Setup
Most cinemas are using a single projector and the RealD Z-filter system to
alternating show left and right images at a swap rate of 144Hz, where the
Z-filter is dynamically modulating the polarization.
Technically the Z-filter is just some large Liquid Crystal Panel. LCs have the
property, to rotate the passing light's polarization plane, depending on a voltage
applied on the LC. The Z-filter thus rotates the light by +/-45°, controlled
by an AC voltage in sync with the left-right-image swap. Before the Z-filter
is a linear polarizer, behind it a λ/4 retarder, in parallel to the linear
polarizer. The Z-filter will rotate the polarization plane to that either only
left or right turning polarized light is leaving the system, if there's stereoscopic
material shown.
If the Z-filter is turned off, the light will be turned into 50% left and 50% right
turning polarization.
It is perfectly possible to recreate this system DIY. This however shall be described
in a separate article still to be written.
Dual Projector Setup
Using two projectors is the most easy way to project the distinct polarized images.
The idea is simple: Each projector is equiped with a polarizing filter matching the
filter in the viewer's glasses eye filters, so that light projected from the "left"
projector will reach only the left eyes, and the "right" projector's light reaches
only the viewer's right eyes.
Selecting the Projectors
It boils down to the following: You need two identical projectors which emit either
unpolarized light - that are DLP projectors using classical arc lamps -
or evenly linear polarized light for all base colours.
The later case is more appealing since you'll not "throw away" light. But the safer
is, choosing some DLP type. Note that those new nifty LED projectors usually exhibit
some uneven polarization, which makes them tricky to next impossible to use for
polarized stereoscopy.
Making the Filter Slides
The projector's filter slides can be made from the very same kind of 3D glasses
which are worn by the viewers. The 3D glasses of RealD are meant for single use.
Although cinemas setup boxes for recycling, there's no harm to the venues if you
put those glasses you got in the cinema to your own use. In fact most cinemas will
have no problem with giving you some of the glasses returned to the recycling boxes.
You may be tempted to just put those filters right behind the projectors lens.
This is however crude and will quickly destroy those filters. Remember that 50% of
the lights power may end up in the filters, heating them up.
So you want to distribute the light's power over a significant large area.
You'll need:
a number of used RealD glasses
4 panes of identically sized picture frame glass (something like 50mm × 50mm)
sharp and exact scissors or a paper guillotine
a fine tip water solvent marker pen (or similar) - whiteboard markers do fine!
some adhesive tape. Duct tape works very well (what, did you expect something else?)
This is how it goes:
In all the 3D glasses mark the back side (i.e. the side towards the eyes)
with a small letter 'L' or 'R' (left eye or right eye), right in the middle.
By applying some twist/torque on the glasses frames you can separate RealD glasses
releasing the filters.
Sort the filters into left and right filters.
Cut the filters into equally sized rectangular pieces sort them into left and right.
Don't make them quadratic. It's important that you still know the orientation within
the glasses' frame.
Clear the marking, making sure you still know what's front and what's back.
Arrange the filter pieces on the glass panes so that they nearly fill it. Of course
all facing the same (i.e. all front or all back).
Keep the gaps as small as possible.
Apply the second glass pane, apply the duck tape along the borders.
You've now left and right polarizing filter slides. Put on 3D glasses of the same making
and determine the orientation in which each pane blocks the light most efficiently by looking
through the filter slide. Important: The filter plane that blocks the light on a eye
looking through it directly will be the slide for projection that particular eye later.
The reason for that is, that reflection changes chirality, i.e. left and right turning are
swapped by reflection.
Setting up the Projection
Align the projectors so that their images match. Vertical alignment must be perfect.
Horizontal alignment may be slightly shifted, but it should be done as good as possible, to.
Place the filters in the light's way. The whole filter area should be used.
Show the stereoscopic material, so that each projector display's its eyes picture.