2 Shooting Questions
I was following a tutorial on shooting and I have the following scripts. The problem I have is when the trigger is not checked on bullet, the bullet fires but hits nothing. If I add the triggered, the bullet goes maybe .5f and then disappears. What am I missing? The second problem is when facing left, the bullet drops to go at foot level. how can I get to shoot at same level either way?
Player Shoot:
private void Update() {
if (Input.GetMouseButtonDown(0) && timeUntilFire < Time.time) {
Shoot();
timeUntilFire = Time.time + fireRate;
}
}
void Shoot() {
float angle = pm.isFacingRight ? 0f : 180f;
Instantiate(bulletPrefab, firingPoint.position, Quaternion.Euler(new Vector3(0f, 0f, angle)));
}
Bullet Script
private void FixedUpdate() {
{
rigidbody.velocity = transform.right * bulletSpeed;
}
}
private void OnCollisionEnter2D(Collision2D other) {
Destroy(gameObject);
}
}
Answer by sztobar · Oct 10, 2020 at 08:02 PM
About the falling bullet - I guess it's because you have added there a
rigidbody2d
component. Such component have gravity by default and will always fall. The fix is super simple - just change`Gravity scale` on it to 0.About the collision, it's more complicated. Does the bullet script have any more code? Have you checked if it doesn't move misteriously on z-axis? About the
isTrigger
bool flag in collider let me quote the official unity docs:A trigger doesn't register a collision with an incoming Rigidbody. Instead, it sends OnTriggerEnter, OnTriggerExit and OnTriggerStay message when a rigidbody enters or exits the trigger volume.
It takes some time to wrap your head around colliders, collision types and how they interact with each other in Unity, you can start by reading about them in the offical docs or trying to watch some videos on yt that explains them. I don't have any particular one that I can recommend, as for me it was a long session of trials-and-erros before I started to understand them to satisfactory level.