小球的碰撞变色事件

简单了解一下什么是材质

材质:是指物体看起来是什么质地,材质可以堪称是材料和质感的结合

我们可以通过他 来调整颜色透明度

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

 这样我们就实现小球的碰撞变色的事件啦~

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值