前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >unity模仿mc放方块

unity模仿mc放方块

作者头像
时光潜流
发布2022-12-26 19:51:41
8340
发布2022-12-26 19:51:41
举报
文章被收录于专栏:博客专栏博客专栏

? ?今天实现了unity技术模仿mc放方块的功能,由于目前是锁定视角的,所以做起来相对来说比较简单。

? ?我实现的逻辑主要就以下的几步:

1. 获取左击事件的触发

2. 从相机向空间中该点发射射线发生碰撞,判断是否是基准方块类型(非方块地基无法放置方块)

3. 获取碰撞面,上面、侧面、前后面(方块中心点到空间点击点的向量,求与各面的垂直向量夹角,若夹角<45°,则该面被点中)

4. 创建实体方块并且移动位置。完工!

? ? 代码:

代码语言:javascript
复制
private void Update(){
	if (Input.GetMouseButtonUp(0)){
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		if (Physics.Raycast(ray, out hit) && (hit.transform.tag.Equals("box"))){
			Transform hitted = hit.transform;

			GameObject temp = newGOByPath(BOX_PATH);
			temp.transform.position = hitted.position;
			BoxCollider collider = temp.GetComponent<BoxCollider>();
			float realSize = collider.size.x / 2;

			Vector3 c2p = hit.point - hit.transform.position;
			float toRD = smallDegree(Vector3.Angle(c2p, Vector3.right));
			float toFD = smallDegree(Vector3.Angle(c2p, Vector3.forward));
			float toUD = smallDegree(Vector3.Angle(c2p, Vector3.up));

			if (toRD <= 45){
				temp.transform.Translate(realSize * Vector3.right);
				Instantiate(temp);
			} else if (toFD <= 45){
				temp.transform.Translate(realSize * Vector3.back);
				Instantiate(temp);
			}
			else if (toUD <= 45){
				temp.transform.Translate(realSize * Vector3.up);
				Instantiate(temp);
			} else{}
		}
	}
}
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-07-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com