Unity2021 realizes the rotation of cubes with different colors and different colors controlled by mouse and keyboard

1. Create a 3D project

2. Create a Cube and a Plane (in fact, it is useless, you can not build it)

3. Create three folders in the Assets of the Project, and put the code files later

4. Set the color.

(1) Right-click in the Material folder to create a Material file named CubeMaterial, which is the first white circle in the figure below. The middle is to control the Plane. If the Plane is not created, there is no need to create this Material.

(2) Right-click and create a Shader file, named Vertrix. Double-click to open the file and edit a piece of code in it. save.

Shader "Custom/Vertrix"
{
    Properties{
	}
	SubShader{
			Pass {
					ColorMaterial AmbientAndDiffuse
			}
	}
}

 (3) Click the CubeMaterial just created, and add the created Shader in the Inspector.

(4) Drag the CubeMaterial to the Cube module and bind the Material

(5) Add a script to control the color change for the Cube. In the Scripts folder, create a C# script file of ColorScript. Drag this script file to Cube and bind the script. Then open the script file to add the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColorScript : MonoBehaviour
{
    public Color[] all_colors;
    private Mesh mesh;

    void Start()
    {
        if (all_colors == null || all_colors.Length <= 0)
            all_colors = new Color[] { Color.red };
        MeshFilter mf = GetComponent<MeshFilter>();
        if (mf == null) return;
        mesh = MakeCube(1.0f);
        mf.mesh = mesh;
        MeshCollider mc = GetComponent<MeshCollider>();
        if (mc != null)
            mc.sharedMesh = mesh;
    }

    public void ChangeColor(int iTriangle)
    {
        Color colorT = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), 1.0f);
        Color[] colors = mesh.colors;
        int iStart = mesh.triangles[iTriangle * 3];
        for (int i = iStart; i < iStart + 4; i++)
            colors[i] = colorT;
        mesh.colors = colors;
    }

    Mesh MakeCube(float fSize)
    {
        float fHS = fSize / 2.0f;
        Mesh mesh = new Mesh();
        mesh.vertices = new Vector3[] {
             new Vector3(-fHS,  fHS, -fHS), new Vector3( fHS,  fHS, -fHS), new Vector3( fHS, -fHS, -fHS), new Vector3(-fHS, -fHS, -fHS),  // Front
             new Vector3(-fHS,  fHS,  fHS), new Vector3( fHS,  fHS,  fHS), new Vector3( fHS,  fHS, -fHS), new Vector3(-fHS,  fHS, -fHS),  // Top
             new Vector3(-fHS, -fHS,  fHS), new Vector3( fHS, -fHS,  fHS), new Vector3( fHS,  fHS,  fHS), new Vector3(-fHS,  fHS,  fHS),  // Back
             new Vector3(-fHS, -fHS, -fHS), new Vector3( fHS, -fHS, -fHS), new Vector3( fHS, -fHS,  fHS), new Vector3(-fHS, -fHS,  fHS),  // Bottom
             new Vector3(-fHS,  fHS,  fHS), new Vector3(-fHS,  fHS, -fHS), new Vector3(-fHS, -fHS, -fHS), new Vector3(-fHS, -fHS,  fHS),  // Left
             new Vector3( fHS,  fHS, -fHS), new Vector3( fHS,  fHS,  fHS), new Vector3( fHS, -fHS,  fHS), new Vector3( fHS, -fHS, -fHS)}; // right

        int[] triangles = new int[mesh.vertices.Length / 4 * 2 * 3];
        int iPos = 0;
        for (int i = 0; i < mesh.vertices.Length; i = i + 4)
        {
            triangles[iPos++] = i;
            triangles[iPos++] = i + 1;
            triangles[iPos++] = i + 2;
            triangles[iPos++] = i;
            triangles[iPos++] = i + 2;
            triangles[iPos++] = i + 3;
        }

        mesh.triangles = triangles;
        int color_index = -1;
        Color colorT = Color.red;
        Color[] colors = new Color[mesh.vertices.Length];
        Debug.Log("test:size=" + all_colors.Length);
        for (int i = 0; i < colors.Length; i++)
        {
            if ((i % 4) == 0)
            {
                color_index++;
                colorT = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), 1.0f);
            }
            //colors[i] = colorT;

            color_index = color_index % all_colors.Length;
            colors[i] = all_colors[color_index];
            colors[i].a = 1.0f;
        }

        mesh.colors = colors;
        mesh.RecalculateNormals();
        return mesh;
    }

}

 (6) Set the color of each face in the Inspector.

So far, a Cube cube with six sides of different colors has been created, and you can see it by clicking Run.

5. Let's write the control code.

 Create a C# script file in the Scripts file. Drag it onto the Cube to bind it. Open it and add the following code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 编辑脚本实现功能:
///从物体角度,通过键盘按键 WSAD 前后左右移动立方体cube
///从物体角度,通过键盘按键 QE 上、左 旋转立方体cube
///从摄像机角度,通过鼠标左键 旋转立方体
/// </summary>

public class CubeScript : MonoBehaviour
{
    Vector3 mPrevPos = Vector3.zero;
    Vector3 mPosDelta = Vector3.zero;

    void Start()
    {
    }

    private void Update()
    {
        float ws = Input.GetAxis("Vertical");  //按‘W’'S'键返回一个[-1,1]的值
        float ad = Input.GetAxis("Horizontal");  //按‘A’'D'键返回一个[-1,1]的值
        this.transform.Translate(Vector3.forward * ws * Time.deltaTime * 7, Space.Self);  //前后移动
        transform.Translate(Vector3.left * ad * Time.deltaTime * 7, Space.Self);  //左右移动

        if (Input.GetKey(KeyCode.Q))  //按下Q
        {
            transform.Rotate(Vector3.up, 1.0f, Space.Self);  //前后旋转
        }
        if (Input.GetKey(KeyCode.E))  //按下E
        {
            transform.Rotate(Vector3.left, 1.0f, Space.Self);  //左右旋转
        }

        if (Input.GetMouseButton(0))  //按下鼠标左键
        {
            mPosDelta = Input.mousePosition - mPrevPos;
            transform.Rotate(Camera.main.transform.up, -mPosDelta.x, Space.World);
            transform.Rotate(Camera.main.transform.right, mPosDelta.y, Space.World);
            //在指定坐标系(参数3,世界坐标系)中,对象绕指定向量(参数1),旋转指定角度(参数2)
            //transform.up 在世界坐标系中的上方向。要搭配使用Space.Word
            //此方法解决了摄像机反向拍摄场景时,旋转坐标系不合理的问题
        }
        mPrevPos = Input.mousePosition;
    }


}

 so far. This project is over. Thanks for the reference.

Guess you like

Origin blog.csdn.net/Yafii/article/details/127480661
Recommended