小白求教,怎么判断我点击了物体的哪个面
unity3d吧
全部回复
仅看楼主
level 6
zhang3520332 楼主
事情是这样的,我想实现一个功能,就是点击正方体的正面,就在正面的方向在生成一个正方体,在点击侧面,又在侧面生成一个正方体,研究一下午了,求指导,在线等
2015年06月01日 09点06分 1
level 12
一个方法,仅仅针对楼主所说的正方形
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public GameObject obj;
public float distance = 1;
// Use this for initialization
void Start () {
if (!obj)
{
Debug.LogError("obj对象为null");
}
if (obj.GetComponent<Collider>())
{
Destroy(obj.GetComponent<Collider>());
}
}
// Update is called once per frame
void Update () {
Ray ray;
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000))
{
Vector3 orign=hit.collider.bounds.center;
Vector3 hitPoint = hit.point;
Vector3 hitPointLocal = hit.collider.gameObject.transform.InverseTransformPoint(hitPoint);
float x = Mathf.Abs(hitPointLocal.x);
float y = Mathf.Abs(hitPointLocal.y);
float z = Mathf.Abs(hitPointLocal.z);
if (x < 0.5) { hitPointLocal = new Vector3(0,hitPointLocal.y,hitPointLocal.z); }
if (y < 0.5) { hitPointLocal = new Vector3(hitPointLocal.x, 0,hitPointLocal.z); }
if (z < 0.5) { hitPointLocal = new Vector3(hitPointLocal.x, hitPointLocal.y,0); }
hitPoint = hit.collider.gameObject.transform.TransformPoint(hitPointLocal);
Vector3 direction =Vector3.Normalize(hitPoint - orign);
Vector3 spwanPoint = hitPoint + direction * distance;
Instantiate(obj,spwanPoint,hit.collider.gameObject.transform.rotation);
}
}
}
}
2015年06月01日 11点06分 2
你好强大!
2023年08月24日 11点08分
感谢
2023年08月24日 11点08分
level 12
2015年06月01日 11点06分 3
level 12
原理:
获取点击在物体上的点。
将改点坐标转化为相对于物体的坐标。
将该点坐标校正到对应面中心点。
将该点转化为世界坐标。
2015年06月01日 11点06分 4
level 12
2015年06月01日 11点06分 5
[真棒]超赞。前端时间忙,一直没来得及感谢您。万分抱歉
2015年07月13日 02点07分
@zhang3520332 [滑稽]不用谢,我当时只是想装逼
2015年07月13日 08点07分
level 9
明显小白不适合做这个功能。看楼上
2015年06月02日 07点06分 6
level 1
射线检测就能做,hit 的信息是正面反面写判断就行了
2023年08月25日 13点08分 7
1