Unet学习

1.创建NetworkManager(空物体),在上面添加NetworkManager组件,添加NetWorkManagerHUD组件

2.创建预制体PlayerPrefab,在上面添加NetworkIdentity,勾选Local Player Authority,在NetWorkManager组件下的SpawnInfo里,将预制件拖入PlayerPrefab上

3。控制移动:添加PlayerController脚本,

4.在Player预制体上添加NetworkTransform,实时同步

5.在子弹上面加NetworkIdentity,同时添加NetworkTransform,将子弹添加到SpawnInfo中

6.制作敌人,添加预制件Enemy

7.添加EnemySpawner

8.添加两个NetworkStartPosition,在NetworkManager里选择RoundRobin

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class Enemyspawner : NetworkBehaviour {

    public GameObject enemyPrefab;
    public int numberOfEnemies;
    public override void OnStartServer()
    {
        for(int i=0;i<numberOfEnemies;i++)
        {
            Vector3 position = new Vector3(Random.Range(-6, 6), 0, Random.Range(-6, 6));
            Quaternion rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);

            GameObject enemy = GameObject.Instantiate(enemyPrefab, position, rotation) as GameObject;

            NetworkServer.Spawn(enemy);
        }
    }
}



using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerController : NetworkBehaviour {

    public GameObject bulletPrefab;
    public Transform firePos;
	
	// Update is called once per frame
	void Update ()
    {
        if(isLocalPlayer==false)
        {
            return;
        }
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        transform.Rotate(Vector3.up * h * 120 * Time.deltaTime);
        transform.Translate(Vector3.forward * v * 3 *Time.deltaTime);
        
        if(Input.GetKeyDown(KeyCode.Space))
        {
            CmdFire();
        }
	}

    [Command]  //called in client run in server
    void CmdFire() //这个方法在Server里面调用
    {
        //子弹生成 需要Server完成 , 然后把子弹同步到Client中
        GameObject bullet = GameObject.Instantiate(bulletPrefab, firePos.position, firePos.rotation);
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 10;
        Destroy(bullet, 2);

        NetworkServer.Spawn(bullet);   //同步到各个客户端
    }
    public override void OnStartLocalPlayer()
    {
        //这个方法只会在本地角色那里调用 当角色被创建的时候
        GetComponent<MeshRenderer>().material.color = Color.blue;
    }
}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour {

    private void OnCollisionEnter(Collision collision)
    {
        GameObject hit = collision.gameObject;
        Health headlth = hit.GetComponent<Health>();
        if(headlth!=null)
        {
            headlth.TakeDamage(10);
        }
        Destroy(this.gameObject);
    }
}




using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class Health : NetworkBehaviour {

    public const int maxHealth = 100;
    [SyncVar(hook ="OnChangeHealth")]
    public int currentHealth = maxHealth;
    public Slider healthSlider;
    public bool DestroyOnDeath = false;

    private NetworkStartPosition[] spawnPoints;

    private void Start()
    {
        if(isLocalPlayer)
        {
            spawnPoints = FindObjectsOfType<NetworkStartPosition>();
        }
    }
    public void TakeDamage(int damage)
    {
        if(isServer==false)   //血量的处理只在服务器端执行
        {
            return;
        }
        currentHealth -= damage;
        if(currentHealth<=0)
        {
            if(DestroyOnDeath)
            {
                Destroy(this.gameObject);return;
            }
            currentHealth = maxHealth;
            Debug.Log("Dead");
            RpcRespawn();
        }
       
    }
    void OnChangeHealth(int health)
    {
        healthSlider.value = health / (float)maxHealth;
    }

    [ClientRpc]     //只在客户端下进行
    void RpcRespawn()
    {
        if(isLocalPlayer==false)      //是否是本地玩家
        {
            return;
        }
        Vector3 spawnPosition = Vector3.zero;
        
        if(spawnPoints!=null && spawnPoints.Length>0)
        {
            spawnPosition = spawnPoints[Random.Range(0, spawnPoints.Length)].transform.position;
        }
        
        transform.position = spawnPosition;
    }
}



using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAt : MonoBehaviour {

	
	
	// Update is called once per frame
	void Update () {
        transform.LookAt(Camera.main.transform);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在训练Unet网络时,学习率的设置是一个重要的超参数,它可以影响模型的收敛速度和性能。以下是几种常用的学习率设置方法: 1. 固定学习率:将学习率设置为一个固定的常数值。这是最简单的设置方式,适用于训练过程中学习率无需调整的情况。例如: ```python from keras.optimizers import Adam lr = 0.001 # 设置学习率 optimizer = Adam(lr=lr) model.compile(optimizer=optimizer, loss='binary_crossentropy') ``` 2. 学习率衰减:随着训练的进行,逐渐降低学习率。可以根据训练的轮数或者验证集上的性能来进行学习率的调整。以下是使用指数衰减方式进行学习率衰减的示例: ```python from keras.optimizers import Adam from keras.callbacks import LearningRateScheduler def lr_decay(epoch): initial_lr = 0.001 # 初始学习率 decay_rate = 0.1 # 衰减率 decay_step = 10 # 衰减步数 lr = initial_lr * (decay_rate ** (epoch // decay_step)) return lr optimizer = Adam() model.compile(optimizer=optimizer, loss='binary_crossentropy') lr_scheduler = LearningRateScheduler(lr_decay) model.fit(X_train, y_train, callbacks=[lr_scheduler]) ``` 3. 动态调整学习率:根据训练过程中的某些指标来动态调整学习率。常用的方法包括基于验证集性能的提升情况、基于损失函数的变化等。以下是使用ReduceLROnPlateau回调函数动态调整学习率的示例: ```python from keras.optimizers import Adam from keras.callbacks import ReduceLROnPlateau optimizer = Adam() model.compile(optimizer=optimizer, loss='binary_crossentropy') lr_scheduler = ReduceLROnPlateau(factor=0.1, patience=3, min_lr=0.00001) model.fit(X_train, y_train, callbacks=[lr_scheduler]) ``` 以上是几种常用的学习率设置方法,具体选择哪种方式取决于数据集、模型和训练任务的特点。根据实际情况进行调试和优化,找到最合适的学习率设置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值