本文主要是介绍Unity2D——捕鱼,炮台锁定辅助线,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
无论是愤怒的小鸟还是泡泡堂,都需要一定的辅助线,捕鱼也不例外,在锁定鱼儿的时候,亦需要辅助线连接炮台与被锁定的鱼儿。
如图所示,创建场景及对象
其中“Image”是待生成泡泡的父体,调整其尺寸(50,1000),位置(0,500,0)
创建一个脚本,CSDN.cs,并添加到“Paotai”对象上,如图所示
其中“paopao”是Resources中的预制体,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class CSDN : MonoBehaviour {Vector3[] Pos;public GameObject Prefab;//鱼public GameObject PaopaoParent;//泡泡父体bool _move = false;//鱼儿是否可移动public GameObject paopao;//泡泡预制体List<GameObject> paopaonum = new List<GameObject>();int oldnum = 0;//目前已显示的泡泡数void Start(){for (int i = 0; i < 20; i++)//生成连线中的泡泡{GameObject go = GameObject.Instantiate(paopao) as GameObject;go.transform.parent = PaopaoParent.transform;go.transform.localScale = Vector3.one;go.transform.localPosition = new Vector3(0, -500 + 80 * (i + 1), 0);go.gameObject.SetActive(false);paopaonum.Add(go);}}void Update(){if (_move){Vector3 lookDirect = Pos[1] - Prefab.transform.position;Quaternion oldQ = Quaternion.LookRotation(Vector3.forward, lookDirect);float oldz = oldQ.eulerAngles.z;Prefab.transform.eulerAngles = new Vector3(0, 0, oldz);//修改鱼儿游动方向Prefab.transform.position = Vector3.MoveTowards(Prefab.transform.position, Pos[1], 50 * Time.deltaTime);//鱼儿移向目标位置MovePaopao(this.transform.position, Prefab.transform.position);//显示和隐藏相对泡泡个数}}public void OnButton(int index){switch (index){case 0:Pos = new Vector3[2];for (int i = 0; i < 2; i++)//随机生成鱼儿可移动的初始位置及目标位置{int _x = Random.Range(-300, 300);int _y = Random.Range(-600, 300);Pos[i] = new Vector3(_x, _y, 0);}Prefab.transform.position = Pos[0];_move = true;//可移动break;}}void MovePaopao(Vector2 v1, Vector2 v2)//v1炮台位置,v2鱼的位置{float dis = Vector2.Distance(v1, v2);float num = Mathf.Floor(dis / 80);//取整,舍去小数点后数字Vector2 targetDir = v2 - v1;float fireangle = Vector2.Angle(targetDir, Vector3.up);if (v2.x > v1.x){fireangle = -fireangle;}this.transform.eulerAngles = new Vector3(0, 0, fireangle);//根据鱼儿位置更改炮台指向角度if (oldnum != (int)num){if (oldnum < (int)num)//当鱼儿游向远处时,显示泡泡{for (int i = oldnum; i < (int)num; i++){paopaonum[i].gameObject.SetActive(true);}}else if (oldnum > (int)num)//当鱼儿游向近处时,隐藏泡泡{for (int i = (int)num; i < oldnum; i++){paopaonum[i].gameObject.SetActive(false);}}oldnum = (int)num;}}
}
对“Button”的设置
1:选择“Button”对象,点击“+”,2:将“Paotai”对象拖入2中,3:选择CSDN中的Button(),4:设置为0;
这篇关于Unity2D——捕鱼,炮台锁定辅助线的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!