1.从指定位置朝着屏幕发射子弹(或其他物体)2.子弹射程设置

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);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值