此刻,我将游戏对象拖到屏幕上;但是,我很难弄清楚如何使我的游戏对象捕捉到场景中预先存在的游戏对象。实例化实例后,如何在运行时将我的游戏对象捕捉到另一个对象?
public class DragObject : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(
gameObject.transform.position).z;
mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
}
private Vector3 GetMouseAsWorldPoint()
{
Vector3 mousePoint = Input.mousePosition;
mousePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
void OnMouseDrag()
{
transform.position = GetMouseAsWorldPoint() + mOffset;
}
}
LoadAssets
类:
public class LoadAssets : MonoBehaviour
{
bool isCreated = false;
bool isCreatedDrillbit = false;
public void LoadBOP()
{
if (!isCreated)
{
GameObject instance = Instantiate(Resources.Load("BOP", typeof(GameObject))) as GameObject;
isCreated = true;
}
}
public void LoadDrillBit()
{
if (!isCreatedDrillbit)
{
GameObject instance = Instantiate(Resources.Load("Drillbit", typeof(GameObject))) as GameObject;
isCreatedDrillbit = true;
}
}
}
答案 0 :(得分:2)
编写一个脚本,该脚本检查其他对象的位置,如果该对象足够靠近,则使其成为其自身的子代,并将其本地位置和旋转设置为默认值。另外,禁用拖动脚本:
public class SnapToMe : MonoBehaviour
{
public GameObject target = null;
public float snapDistance = 1f;
void FixedUpdate()
{
if (target==null) return;
if ( Vector3.Distance(transform.position, target.transform.position) <= snapDistance) )
{
target.transform.parent = transform;
target.transform.localRotation = Quaternion.identity;
target.transform.localPosition = Vector3.zero;
target.GetComponent<DragObject>().enabled = false;
}
}
}
在要执行捕捉的对象上,在应该发生捕捉的位置添加一个子对象,然后将捕捉脚本附加到该对象:
Bottle
└── Bottle snap point
└── SnapToMe
然后在创建盖子时,告诉它有关的要点:
Gameobject newCap = Instantiate(...);
Gameobject bottleSnapPoint = GameObject.Find(
"Bottle snap point"); // or some other way to get a reference to the snap point
SnapToMe snapper = bottleSnapPoint.GetComponent<SnapToMe>();
snapper.target = newCap;
snapper.snapDistance = 2f; //whatever is appropriate