[英]Snapping game object to another game object in Unity 3D during runtime
At this moment, I drag my game-object across the screen;此刻,我将我的游戏对象拖过屏幕; however, I'm having a hard time figuring out how to have my game-object snap to pre-existing game-object in my scene.
但是,我很难弄清楚如何让我的游戏对象捕捉到场景中预先存在的游戏对象。 How do I have my game-object snapped to another object during run time once it is instantiated?
实例化后,如何在运行时将我的游戏对象捕捉到另一个 object?
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
class:加载资产
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;
}
}
}
Write a script that checks the position of some other object, and if it's close enough, make it a child of itself and set its local position and rotation to be the default.编写一个脚本来检查其他一些 object 的 position,如果它足够接近,则使其成为自身的子节点,并将其本地 position 和旋转设置为默认值。 Also, disable the dragging script:
另外,禁用拖动脚本:
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;
}
}
}
On the object you'd like to do the snapping, add a child object where the snapping should occur, and attach the snapping script to it:在您想要进行捕捉的 object 上,在应该发生捕捉的位置添加一个子 object,并将捕捉脚本附加到它:
Bottle
└── Bottle snap point
└── SnapToMe
Then when you create the cap, tell the snap point about it:然后,当您创建上限时,请告诉快照点:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.