Bắn đạn theo đường thẳng
C# Code
using UnityEngine;
public class SimpleShooter : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform firePoint; // Nơi đạn được tạo ra
public float bulletSpeed = 20f;
void Update()
{
if (Input.GetButtonDown("Fire1")) // Nút chuột trái hoặc Ctrl trái
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody rb = bullet.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = firePoint.forward * bulletSpeed;
}
// Hủy viên đạn sau một khoảng thời gian để tránh làm đầy scene
Destroy(bullet, 5f);
}
}Tạo một viên đạn (projectile) tại một điểm và bắn nó đi theo một hướng xác định. Thường dùng cho nhân vật hoặc kẻ địch.