Cast and Receive Shadows
-
Introduction
Everything around us would cast some shadows (unless it is totally dark), so adding shadows will make your 3D scene more realistic.
However, it takes extra time and computation power to calculate and draw shadows. Therefore, an object would not cast any shadow by default, and you have to specify which objects will cast shadows using code blocks.
As shown above, to generate a shadow, you actually need to specify 3 things:
- A light source: The light that will be used to calculate the shadow
- A shadow-casting object: The object that will be casting the shadow, such as a flower or an avatar
- A shadow-receiving object: The object that will receive the shadow. This is where the shadow will be drawn, such as a table or a floor.
Light Source
You can only use the directional light or the point light as the light source for calculating shadows. When you add the light, it is recommended that you give the light a name, so that we can refer to this light later.
Note that you might need to remove all existing lights in the scene before you add the light source for the shadow, otherwise the shadow might be too dim to see.
In addition, the position of the light source should be above the shadow-casting object and the shadow-receiving object. Otherwise, no shadow will be generated.
Here is an example program:
Set an Object to Cast Shadow
To make an object cast some shadow, you need to run the following block. It will make the current active sprite object cast a shadow, so normally you should run this block right after you add the shadow-casting object.
It accepts 3 inputs:- Yes/No: If this input is “Yes”, then the sprite object will cast a shadow. If this input is “No”, then the sprite object will stop casting shadows.
- Light Source Name: the name of the light source. If it is blank, then the light source that’s added the last will be used.
- Blur Size: this number controls how blurry the shadow is. Normally shadows have blurry edges.
Set an Object to Receive Shadows
After you add the light source and shadow-casting object, you will still not see any shadows drawn anywhere. That’s because we have not specified where the shadow will be displayed.
To set an object to receive and display shadows, you need to use the following block:
If the input is “Yes”, then the current sprite object will be used to display shadows; otherwise, the sprite object will stop displaying shadows.
Demo 1
In this program, we go through these 3 steps:
- Add a point light named “light1” to serve as the light source
- Add a flower object that will cast a shadow
- Add a table object that will receive the shadow
You will get the following result:
Demo 2
In this program, we go through these 3 steps:
- Add a directional light named “light1” to serve as the light source
- Add a dancing avatar that will cast a shadow
- Add a floor using a plane object that will receive the shadow
You will get the following result: -