2022-07-23 21:03:50
今天实现了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{}
}
}
}