c# - 在运行时将游戏对象捕捉到 Unity 3D 中的另一个游戏对象
问题描述
此刻,我将我的游戏对象拖过屏幕;但是,我很难弄清楚如何让我的游戏对象捕捉到场景中预先存在的游戏对象。实例化后,如何在运行时将我的游戏对象捕捉到另一个对象?
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;
}
}
}
解决方案
编写一个脚本来检查其他对象的位置,如果它足够近,则使其成为自身的子对象,并将其本地位置和旋转设置为默认值。另外,禁用拖动脚本:
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
推荐阅读
- javascript - 为什么每个生产部署都需要清除浏览器缓存
- java - Onesignal 和 play-services-ads 错误:无法在单个 dex 文件中容纳请求的类
- docker - 进程可以在 Windows 上写入 docker 卷,而不是在 Ubuntu 上
- android - ViewPager2 在键盘出现时调整大小
- javascript - 如何更改嵌入文本的字体大小
- jsf - 检查复选框菜单中的选定项目
- sql - 尝试将外键添加到现有表时出现模糊错误
- kubernetes - 强制 kubernetes 入口 cname 格式
- react-native - 如何在 React Native 中加入 2 个堆栈导航器
- php - laravel 5.5 禁止/停用用户