今天实现了unity技术模仿mc放方块的功能,由于目前是锁定视角的,所以做起来相对来说比较简单。
我实现的逻辑主要就以下的几步:
1. 获取左击事件的触发
2. 从相机向空间中该点发射射线发生碰撞,判断是否是基准方块类型(非方块地基无法放置方块)
3. 获取碰撞面,上面、侧面、前后面(方块中心点到空间点击点的向量,求与各面的垂直向量夹角,若夹角<45°,则该面被点中)
4. 创建实体方块并且移动位置。完工!
代码:
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{}
}
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有