c# - 物体不动,如何让子弹动起来
问题描述
我制造了一个会向玩家射击的敌人。我在水池出现时转动它并尝试启动它,但由于某种原因它没有移动
我有两个用于子弹脚本的脚本,一个用于射击子弹的敌人的脚本
起初,我试图在AddForce(transform.up * Speed);
对于子弹
public class BulletScript : MonoBehaviour
{
public GameObject bullet;
void Start()
{
bullet.transform.Translate(bullet.transform.forward * Time.deltaTime);
}
}
为敌人
public class TurelScript : MonoBehaviour
{
public Transform Player;
public Transform Turell;
public GameObject PrefabOfbullet;
public Transform BUlletPosition;
public float Rotation;
void Start()
{
var turnOfBullet = Quaternion.Lerp(BUlletPosition.rotation, Quaternion.LookRotation(Vector3.forward, Player.position - BUlletPosition.position), Time.deltaTime * 40f);
var rigidbodyBullet = GetComponent<Rigidbody2D>();
StartCoroutine(BulletSpawn());
}
// Update is called once per frame
void Update()
{
var turn = Quaternion.Lerp(Turell.rotation, Quaternion.LookRotation(Vector3.forward, Player.position - Turell.position), Time.deltaTime * 4f);
var rigidbody = GetComponent<Rigidbody2D>();
rigidbody.MoveRotation(turn.eulerAngles.z);
}
IEnumerator BulletSpawn()
{
while (true)
{
Instantiate(PrefabOfbullet, BUlletPosition.position, Turell.rotation);
yield return new WaitForSeconds(0.3f);
}
}
}
解决方案
由于子弹似乎是Rigidbody2D
您根本不应该使用Transform.Translate
的,而只能通过Rigidbody2D
组件更改它并且FixedUpdate
不破坏物理。(见Rigidbody2D.MovePosition
)
然后对于你几乎不想使用AddForce
的子弹,它需要知道子弹的质量并相应地计算所需的力。
你会立即改变它velocity
,所以宁愿做类似的事情
// Having the correct type allows you only to reference
// Object that actually have this type
// And second you don't need `GetComponent` on runtime
public Rigidbody2D PrefabOfBullet;
// Set the speed you want in Unity Units / second
public float BulletSpeed = 1f;
...
var bullet = Instantiate (PrefabOfBullet, Bullet position.position, Turell.rotation);
bullet.velocity = bullet.transform.up * BulletSpeed;
...
推荐阅读
- python - list[::] 和 list 有什么区别?
- python - sys.version_info 对于 Python 版本检查是否可靠?
- xamarin - iPhone X 启动画面上安全区域显示的背景图像
- c - 作为 C 指针的 a 和 a + 0 有什么区别?
- python - 遍历cython中的指定轴
- c# - 当 Quartz 作业运行时出现“对象引用未设置为对象的实例”时出错
- vhdl - 如果合成器报告错误的行号,我如何找到重复的信号定义?
- ios - Swift CollectionView(致命错误:索引超出范围)
- python - python pandas到csv文件保存,不覆盖
- reactjs - 使用 ErrorBoundary 组件在同一页面上反应 JS shwo 错误