The color change event of the collision of the ball

Simply understand what is material

Material: refers to what texture an object looks like. Material can be called a combination of material and texture.

We can adjust the color and transparency through him

ok

Let us implement the collision event of the ball today

First we create three 3D objects under the Hierarchy level

They are: Sphere, Plane, Cube

Conveniently rename Cube to Wall

 

Click on the Cube in the Scene view

Press the R key and stretch along the Z (blue) axis to reach the same length as the Plane

and drag it to the specified location

 Create Scripts file to write Collision script

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

public class Collision : MonoBehaviour
{
    //私有化一个材质
    private Material m_Material;
    private Rigidbody m_PlayerRigid;
    private float force = 10f;
    void Start()
    {   //获得GetComponent的渲染组件
        m_Material = GetComponent<Renderer>().material;
        //将组件拿到内存空间里面并
        m_PlayerRigid = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        //水平运动
        float horizontalX = Input.GetAxis("Horizontal");
        //垂直运动:z轴永远默认为正反向
        float verticalZ = Input.GetAxis("Vertical");
        m_PlayerRigid.AddForce(new Vector3(horizontalX, 0, verticalZ) * force);
    }

    //碰撞接触瞬间的函数
    private void OnCollisionEnter(UnityEngine.Collision other)
    {
        if (other.collider.name == "Wall")
        {
            m_Material.color = Color.red;
        }
    }
    //碰撞黏在一起的时候执行
    /*private void OnCollisionStay(UnityEngine.Collision other)
    {
        if (other.collider.name == "Wall")
        {
            m_Material.color = Color.black;
        }
    }*/
    //碰撞离开时执行
    private void OnCollisionExit(UnityEngine.Collision other)
    {
        if (other.collider.name == "Wall")
        {
            m_Material.color = Color.white;
        }
    }
}

We pass the AddComponent at the bottom of the Inspector view

Mount the script on the ball and add a rigid body component: Rigidbody

 In this way, we can realize the event of the collision and discoloration of the ball~

 

Guess you like

Origin blog.csdn.net/Cddmic/article/details/126363639