c# - 从对象池中旋转游戏对象
问题描述
我想在创建子弹对象后旋转它(即从池中取出)。
这是我的函数,其中子弹从对象池中取出并分别定位:
void CreateBullet (GameObject bulletObj, Transform _bulletPos, float xVal = 0f, float yVal = 0f) {
//get bullet object from pool
bulletObj = bulletPool.GetInstance (playerShotsGO);
bulletObj.transform.position = _bulletPos.position;
Vector2 pos = bulletPos.transform.position;//Position 0,0
pos.x += xVal;
pos.y += yVal;
bulletObj.transform.position = pos;
bulletObj.transform.SetParent (playerShotsGO.transform, true);
}
这是我的 PlayerBullet 脚本的更新函数,其中计算了子弹的位置:
void Update () {
Vector2 position = transform.position;
//compute the bullet's new position
position = new Vector2 (position.x, position.y + speed * Time.deltaTime);
//update the bullet's position
transform.position = position;
}
在这里我的对象被实例化:
protected virtual GameObject AllocateInstance (bool parent, GameObject parentObj) {
GameObject instance = (GameObject)GameObject.Instantiate (prefab);
if (parent) {
instance.transform.SetParent(parentObj.transform, true);
}
instance.SetActive(false);
pool.Add(instance);
return instance;
}
解决方案
根据Unity3d 教程中的https://unity3d.com/learn/tutorials/topics/scripting/object-pooling,您需要在池中搜索准备好使用的对象。如果没有找到,则生成一个新的。然后您使用SetActive(true)
来显示它,并通过 设置旋转instance.transform.rotation = <Vector3>
。
推荐阅读
- sql - 仅在事务完成后强制执行数据完整性
- youtube - 有没有办法在 discord.js 中获取链接到用户的 youtube 频道的 ID?
- javascript - 使用filesInput再次执行事件时如何重新生成DIV?
- python - 使用python将txt文件转换为Excel
- json - 来自 ASP.NET Core api 的 Angular JSON GET 请求的问题
- c# - 如何添加数据并返回结果
- rust - 如何为我不拥有的类型实现 serde 并让它支持复合 /wrapper/collection 类型
- java - 如何通过仅替换一位数字来找到 2 个整数的最大和?
- javascript - 即使使用扩展运算符,您也可能在组件渲染函数中有无限更新循环
- c# - 使用事件触发 Azure 函数,如何使用 c# 将 csv 文件转换为 parquet 文件