为实现游戏背景重复使用,并跟随摄像机移动,采用以下脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OwnFloorControl : MonoBehaviour
{
//摄像机
private GameObject main_camera = null;
//初始位置
private Vector3 initial_position;
//背景组件宽度(X轴方向)
public const float WIDTH = 10.0f * 4.0f;
//背景组件个数
public const int MODEL_NUM = 3;
// Use this for initialization
void Start()
{
//组件应该附在背景上?
//主角武士上?
//cs是单个背景的component,背景根据主摄像头移动,主摄像头跟随主角移动
this.main_camera = GameObject.FindGameObjectWithTag("MainCamera");
this.initial_position = this.transform.position;
}
// Update is called once per frame
void Update()
{
//整体背景宽度 #宽度x个数
float total_width = OwnFloorControl.WIDTH * OwnFloorControl.MODEL_NUM;
//背景组件的位置
Vector3 floor_position = this.transform.position;
//摄像机的位置
Vector3 camera_position = this.main_camera.transform.position;
if (floor_position.x + total_width / 2.0f < camera_position.x)
{
//画布中部在相机位置左
//向前移动
floor_position.x += total_width;
this.transform.position = floor_position;
}
}
}
效果