【Unity】Unity实验入门及碰撞检测
程序员文章站
2022-07-12 23:03:31
...
——————————
Unity入门实验
- 创建项目;
- 点击Hierarchy界面的Creat,添加Cube、Cylinder、Plane;
- 在Inspector界面Transform调整Cube、Cylinder、Plane和Directional Light的位置坐标、光线朝向等;
- 改变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在游戏中的颜色;
- 接下来用另一种方法改变Cylinder的颜色:点击Project界面Create,添加Material,挑选一个颜色,再将其拖到Cylinder上,即改变Cylinder的颜色;
- 给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移动。
碰撞检测
给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消失,完成检测。
上一篇: 物体碰撞预测及检测
下一篇: MoveIt!规划场景