简单了解一下什么是材质
材质:是指物体看起来是什么质地,材质可以堪称是材料和质感的结合
我们可以通过他 来调整颜色和透明度
ok
让我们今天来实现小球的碰撞事件
首先我们在Hierarchy层级下创建 三个3D物体
分别是:Sphere、Plane、Cube
顺手将Cube重命名为Wall
点击Scene视图里的Cube
按下R键,并沿着Z(蓝色)的轴拉长,达到跟Plane一样长
并拖拽到指定位置
创建Scripts文件书写碰撞Collision脚本
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;
}
}
}
我们通过Inspector视图最下面的AddComponent
将脚本挂载到小球身上,并且添加刚体组件:Rigidbody
这样我们就实现小球的碰撞变色的事件啦~