1.从指定位置朝着屏幕发射子弹(或其他物体)
发射位置为枪口,发射方向朝着屏幕中心,发射速度可调。
在按下右键的前提下,点击左键才会发射子弹。
该代码挂载在全局空物体上即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class d_ShootBullet : MonoBehaviour
{
public GameObject bulletPrefab; // 子弹预制体
/// <summary>
/// 子弹射速
/// </summary>
private float bulletSpeed; // 子弹速度
public GameObject standposi; // 子弹发射位置
bool readyShoot;//是否准备射击即是否点击右键架枪
private void Start()
{
bulletSpeed = 7f;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
readyShoot = true;
}
if (Input.GetMouseButtonUp(1))
{
readyShoot = false;
}
if (Input.GetMouseButtonDown(0) && readyShoot) // 检测鼠标左键按下
{
Shoot();
}
}
/// <summary>
/// 发射子弹
/// </summary>
void Shoot()
{
// 创建子弹对象
GameObject bullet = Instantiate(bulletPrefab, standposi.transform.position, Quaternion.identity);
// 获取屏幕中心的位置
Vector3 screenCenter = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f));
// 计算子弹的朝向
Vector3 direction = screenCenter - standposi.transform.position;
// 应用朝向
bullet.transform.rotation = Quaternion.LookRotation(direction);
//子弹速度
Vector3 initialVelocity = direction.normalized * bulletSpeed;
Rigidbody rb = bullet.GetComponent<Rigidbody>(); // 获取子弹的刚体
rb.velocity = initialVelocity * bulletSpeed; // 设置子弹的速度
}
}
2.子弹射程设置
子弹距离玩家一段距离之后,自动摧毁,射程可自行设置
该代码挂载到子弹预支体上
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class d_DestoryBullet : MonoBehaviour
{
private Transform player;
/// <summary>
/// 子弹的射程
/// </summary>
private int canShootDistance;
// Start is called before the first frame update
void Start()
{
canShootDistance = 10;
player = GameObject.Find("player").gameObject.transform;
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(transform.position, player.position);
if (distance > canShootDistance)
{
Destroy(gameObject);
}
}
}