赞
踩
:制作跟随玩家位置动态加载的无限海洋,实时生成新的海平面,又实时销毁。
unity的操作是先制作一个water,将其改成平面的形状(可以直接修改他的MeshFilter选择成Plane即可);
也可以先添加一个平面,将Water的材质赋给平面,也能制作出四边形的水。
game界面是一望无际的水:
话不多说,开始代码吧:
using System.Collections; using System.Collections.Generic; using UnityEngine; //这里的方法是先创建一个用来控制参数的类 class Tile { public GameObject theTile; public float creationTime; //记录生成时间 public Tile(GameObject t, float ct) { theTile = t; creationTime = ct; } } public class GenerateInfinite : MonoBehaviour { public GameObject plane; //获取平面 public GameObject player; //获取玩家 int planeSize = 10; //平面尺寸,默认为10x10 int halfTiles = 10; int halfTilesX = 10; int halfTilesZ = 10; //这里是生成的平面空间大小 Vector3 startPos; //开始位置的坐标向量 Hashtable tiles = new Hashtable();//定义一个哈希表 // Use this for initialization void Start () { this.gameObject.transform.position = Vector3.zero; startPos = Vector3.zero; float updateTime = Time.realtimeSinceStartup;//游戏开始的时间,单位:S for (int x = -halfTilesX; x < halfTilesX; x++)//x方向新增平面生成的空间范围 { for (int z = -halfTilesZ; z < halfTilesZ; z++)//x方向新增平面生成的空间范围 { //计算插入的位置向量 Vector3 pos = new Vector3((x * planeSize + startPos.x), 0, (z * planeSize + startPos.z)); //插入平面 GameObject t = (GameObject)Instantiate(plane, pos, Quaternion.identity);//Quaternion.identity表示插入的时候不要有旋转 //为每一个新生成的平面命名“Tile+坐标”的形式 string tileName = "Tile_" + ((int)(pos.x)).ToString() + "_" + ((int)(pos.z)).ToString(); t.name = tileName; Tile tile = new Tile(t, updateTime); tiles.Add(tileName, tile); } } } // Update is called once per frame void Update () { //跟随玩家的X/Z坐标进行移动 int xMove = (int)(player.transform.position.x - startPos.x); int zMove = (int)(player.transform.position.z - startPos.z); if (Mathf.Abs(xMove)>=planeSize||Mathf.Abs(zMove)>=planeSize) { float updateTime = Time.realtimeSinceStartup; //将X 、Z坐标取整 int playerX = (int)(Mathf.Floor(player.transform.position.x / planeSize) * planeSize);//mathf.floor为向下取整 int playerZ = (int)(Mathf.Floor(player.transform.position.z / planeSize) * planeSize); for (int x = -halfTilesX; x < halfTilesX; x++) { for (int z = -halfTilesZ; z < halfTilesZ; z++) { Vector3 pos = new Vector3(x * planeSize + playerX, 0, (z * planeSize + playerZ)); string tileName = "Tile_" + ((int)(pos.x)).ToString() + "_" + ((int)(pos.z)).ToString(); //将tileName与哈希表的表名对比 if (!tiles.ContainsKey(tileName)) { GameObject t = (GameObject)Instantiate(plane, pos, Quaternion.identity); t.name = tileName; Tile tile = new Tile(t, updateTime); tiles.Add(tileName, tile); } else { (tiles[tileName] as Tile).creationTime = updateTime; } } } Hashtable newTerrain = new Hashtable();//新建哈希表 foreach (Tile tls in tiles.Values) { if (tls.creationTime != updateTime) { Destroy(tls.theTile);//随时销毁,避免资源的浪费 } else { newTerrain.Add(tls.theTile.name, tls); } } tiles = newTerrain; startPos = player.transform.position; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。