我可以通过RayCast
放置一个对象,但它将对象放在彼此内。 我希望它能够检测到碰撞,以便如果某个对象位于该对象之下,那么它必须将新对象放在其上。或者如果在左边碰撞,它必须在右边放置对象。
这是我的代码
using UnityEngine;
using System.Collections;
public class targetPosition : MonoBehaviour {
public GameObject obj;
Vector3 newPosition;
void Start () {
newPosition = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) //It places cube on left click
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
newPosition = hit.point;
GameObject obj1 = Instantiate(obj,newPosition, Quaternion.identity) as GameObject;
obj1.SetActive (true);
}
}
if (Input.GetMouseButtonDown (1)) //deletes cube on right click
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
}
}
}
}
感谢。
答案 0 :(得分:0)
使用此代码,您可以检测光线射击的物体的哪一侧。从那时起,您需要使用该点的某个偏移量来实例化您的对象。
Vector3 normalOfHit;
void Update()
{
if (Input.GetMouseButtonDown(0)) //It places cube on left click
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
normalOfHit = hit.normal;
normalOfHit = hit.transform.TransformDirection(normalOfHit);
if(normalOfHit == hit.transform.up)
{
Debug.Log("Hit top side");
}
if (normalOfHit == -hit.transform.up)
{
Debug.Log("Hit bottom side");
}
if (normalOfHit == hit.transform.right)
{
Debug.Log("Hit right side");
}
if (normalOfHit == -hit.transform.right)
{
Debug.Log("Hit left side");
}
if(normalOfHit == hit.transform.forward)
{
Debug.Log("Hit front side");
}
if(normalOfHit == -hit.transform.forward)
{
Debug.Log("Hit back of object");
}
}
}
}