Unity3d Creating a Dynamic Cube Chart system
This article mainly uses the previous article Shader, through the script to complete a dynamic cube chart change system.
The preparatory work is as follows:
- Create a new scene, a sphere. Provides a parallel light to the scene, preparing 2 cubic graphs .
- Add two empty objects, named Empty1 and Empty2, and assign them a different location .
- Add a new material to the sphere and use the Fresnelreflection Shader (previous article).
- Finally, create a script that is named CubeDynamic.cs andassign it to the sphere.
A: Start writing the script below:
2 cubic graphs ;
Public Cubemap Cubemapa;
Public Cubemap CUBEMAPB;
2 Reference positions Empty1,2;
Public Transform PosA;
Public Transform PosB;
Private Material Tempmat;
Private Cubemap Tempcubemap;
private int times = 0;
B: In order to conveniently observe the position of Empty1,2 , we use the Ondrawgizmos function to draw the object:
void Ondrawgizmos () {
Gizmos.color = Color.green;
if (PosA) {
Gizmos.drawwiresphere (posa.position,5);
}
if (PosB) {
Gizmos.drawwiresphere (posb.position,5);
}
}
C: Create a new function to determine which Cubemap we should use in different locations
Private Cubemap Getusecubemap () {
float Lengtha = vector3.distance (transform.position,posa.position);
float LENGTHB = vector3.distance (transform.position,posb.position);
if (LENGTHA>LENGTHB) {
return CUBEMAPB;
}
else if (Lengtha < LENGTHB)
{
return Cubemapa;
}
else {
return Cubemapa;
}
}
D: Assigning values in the Update function
void Update () {
times++;
if (times%20==0) {// avoid calculating each frame ;
Tempmat = renderer.sharedmaterial;
if (Tempmat)
{
Tempcubemap = Getusecubemap ();
Tempmat.settexture ("_cubemap", Tempcubemap);
}
Times = 0;
}
}
Save the script and return to the Unity Editor. Click the Play button and move the sphere left and right. You will see an effect similar to the following :
With the simple code above, we can see that the program will fix the frame number to a time period to determine the distance between the sphere and 2 reference positions to calculate which cubemapto use, and then CubeMap assignment to himself. This completes the simple transformation.
Unity3d creating a dynamic Cube chart system