【Unity3D-Mirror多人坦克大战】子弹及其开火位置的生成、子弹开火逻辑(四)

15、子弹开火的逻辑

在Player.cs中添加
public class Player : NetworkBehaviour
{
    ……
    
    private float nextFire; //下一次开火的时间
    public float fireRate = 0.75f; //两次开火至少相隔的时间
    public Transform shotPos; // 开火位置
    
    ……

    private void FixedUpdate()
    {
        ……
        
        //开火
        if (Input.GetButton("Fire1"))
        {
            if (Time.time > nextFire)
            {
                nextFire = Time.time + fireRate;
                CmdShoot((short) (shotPos.position.x * 10), (short) (shotPos.position.z * 10));
            }
        }
        
    }
    
    ……
    
    [Command]
    void CmdShoot(short xPos, short zPos)
    {
        Vector3 shotCenter =
            Vector3.Lerp(shotPos.position, new Vector3(xPos / 10f, shotPos.position.y, zPos / 10f), 0.6f);
        // 创建子弹,并同步到客户端

        // 所有客户端进行特效显示
        
    }
    
    [ClientRpc]
    protected void RpcOnShot()
    {
        // 显示特效
    }
}

16、子弹开火位置的设置

在炮台下建立子对象,开火位置ShotPos,放置炮台口

17、场景中子弹生成

新建一个3D球形,让子弹成为它的子对象,命名为Bullet,并删除Mesh Renderer,在3D球形上添加刚体实现碰撞机制,然后添加网络ID和位置同步的组件。
新建Bullet.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Bullet : NetworkBehaviour
{
    public float speed = 15;
    private Rigidbody myRigidbody;
    private void Awake()
    {
        myRigidbody = GetComponent<Rigidbody>();
    }
    private void Start()
    {
        myRigidbody.velocity = speed * transform.forward;
    }
}
Bullet.cs添加到Bullet对象上
保存成预制体,并在场景中删除
在Player.cs继续完善子弹发射逻辑
public class Player : NetworkBehaviour
{
    ……
    
    public GameObject BulletPrefab; //
    
    ……

    ……
    
    ……
    
    [Command]
    void CmdShoot(short xPos, short zPos)
    {
        Vector3 shotCenter =
            Vector3.Lerp(shotPos.position, new Vector3(xPos / 10f, shotPos.position.y, zPos / 10f), 0.6f);
        // 创建子弹,并同步到客户端
        GameObject obj = Instantiate(BulletPrefab, shotCenter, Quaternion.Euler(0, turret.eulerAngles.y, 0)); //把预制体实例化出子弹
        NetworkServer.Spawn(obj,obj.GetComponent<NetworkIdentity>().assetId); // 在服务器端生成,并同步
        // 所有客户端进行特效显示
        RpcOnShot();
    }
    
    [ClientRpc]
    protected void RpcOnShot()
    {
        // 显示特效
    }
}
由于预制体子弹会在服务器中生成,所以需要提前注册

测试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~Lomiss~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值