Gun2D.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun2D : MonoBehaviour { public Transform bulletSpawnPoint; public GameObject bulletPrefab; public float bulletSpeed = 10; void Update() { if (Input.GetKeyDown(KeyCode.Space)) { var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation); bullet.GetComponent<Rigidbody2D>().velocity = bulletSpawnPoint.up * bulletSpeed; } } } |
Bullet.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float life = 3; void Awake() { Destroy(gameObject, life); } void OnCollisionEnter2D(Collision2D collision) { Destroy(collision.gameObject); Destroy(gameObject); } } |