欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Unity】Unity实验入门及碰撞检测

程序员文章站 2022-07-12 23:03:31
...


——————————

Unity入门实验

  1. 创建项目;
  2. 点击Hierarchy界面的Creat,添加Cube、Cylinder、Plane;【Unity】Unity实验入门及碰撞检测
  3. 在Inspector界面Transform调整Cube、Cylinder、Plane和Directional Light的位置坐标、光线朝向等;
  4. 改变Cube颜色:点击Project界面的Create,添加C# Script,改名CubeColor,双击打开,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CubeColor : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        this.GetComponent<Renderer>().material.color = Color.blue;
    }

    // Update is called once per frame
    void Update()
    {
        this.GetComponent<Renderer>().material.color = Color.blue;
    }
}

再将CubeColor拖到Cube上,这样就改变了Cube在游戏中的颜色;【Unity】Unity实验入门及碰撞检测

  1. 接下来用另一种方法改变Cylinder的颜色:点击Project界面Create,添加Material,挑选一个颜色,再将其拖到Cylinder上,即改变Cylinder的颜色;
  2. 给Cube添加脚本:Create -> C# Script,改名CubeController,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CubeController : MonoBehaviour
{
    private Transform m_Transform;
    // Start is called before the first frame update
    void Start()
    {
        m_Transform = gameObject.GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        MoveControl();
    }

    void MoveControl()
    {
        if(Input.GetKey(KeyCode.UpArrow))//向上箭头控制向前移动
        {
            m_Transform.Translate(Vector3.forward * 0.1f, Space.Self);
        }
        if(Input.GetKey(KeyCode.DownArrow))//向下箭头控制向后移动
        {
            m_Transform.Translate(Vector3.back * 0.1f, Space.Self);
        }
        if(Input.GetKey(KeyCode.LeftArrow))//向左箭头控制向左移动
        {
            m_Transform.Translate(Vector3.left * 0.1f, Space.Self);
        }
        if(Input.GetKey(KeyCode.RightArrow))//向右箭头控制向右移动
        {
            m_Transform.Translate(Vector3.right * 0.1f, Space.Self);
        }
        if (Input.GetKey(KeyCode.W))//W键控制向上移动
        {
            m_Transform.Translate(Vector3.up * 0.1f, Space.Self);
        }
        if (Input.GetKey(KeyCode.S))//S键控制向下移动
        {
            m_Transform.Translate(Vector3.down * 0.1f, Space.Self);
        }
    }
}

将CubeController拖到Cube上,即可用上、下、左、右、W、S键控制Cube移动。
【Unity】Unity实验入门及碰撞检测

碰撞检测

给Cylinder添加碰撞检测,即被碰撞后消失:Create -> C# Script,改名Cylinder,代码如下:

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

public class Cylinder : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnCollisionEnter(Collision collision)
    {
        Destroy(this.gameObject);
    }

}

将其拖到Cylinder上。运行:控制Cube移动,当碰到Cylinder时Cylinder消失,完成检测。