Question by
$$anonymous$$ · Aug 30, 2021 at 06:30 AM ·
2dshootingbullets
Help Spawn Bullet 2D
Please help me edit these code to make bullets fly straight up, and when bullets fly off the screen, they are destroyed.
PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Vector3 destination;
private bool isShooting;
[SerializeField]
private float fireRate = 0.2f;
[SerializeField]
private GameObject bulletPrefab;
[SerializeField]
private Transform bulletSpawnPoint;
public AudioSource shootSFX;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
destination = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = Vector3.Lerp(transform.position, new Vector3(destination.x, destination.y, transform.position.z), 0.1f);
}
if (isShooting)
{
StartCoroutine(Shoot());
}
}
IEnumerator Shoot()
{
// Initialize a bullet at the position of bulletSpawnPoint, the angle (Quaternion) defaults to the angle of bulletPrefab
Instantiate(bulletPrefab, bulletSpawnPoint.position, Quaternion.identity);
// Make sound
shootSFX.Play();
// After spawning bullets, will stop firing for #fireRate
isShooting = false;
yield return new WaitForSeconds(fireRate);
// After waiting enough time #fireRate will start firing again
isShooting = true;
}
}
Bullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[SerializeField]
private float bulletSpeed;
[SerializeField]
private float bulletDamage;
// Start is called before the first frame update
void Start()
{
GetComponent<Rigidbody2D>().AddForce(Vector2.up * bulletSpeed);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Block"))
{
Debug.Log("OnTriggerEnter2D with Block");
collision.SendMessageUpwards("OnDamaged", bulletDamage);
}
if (!collision.CompareTag("Bullet"))
{
Destroy(gameObject);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
2D topdown projectiles movement 0 Answers
FindChild not working - Unity 5.5 2D 0 Answers
How do i make an ai shoot? 2D 1 Answer
How do I get my character to shoot towards my mouse in a 2D top down? 0 Answers
Isometric shooter - Bullets 1 Answer