射击类游戏--射击辅助线的实现
程序员文章站
2022-05-27 13:45:54
...
最近在项目中碰到一个问题,炮台再射击物体的时候,要生成一个炮台和目标的辅助线。类似于捕鱼类游戏,在锁定目标的情况下,生成的辅助线。
因为项目是3D的,所以在生成这个辅助线的时候,思考了一个下午,才得以实现。效果如下图:
移动的Cube为锁定的目标,不懂得Cube为射击点。小球 为辅助线。
通过计算射击点和目标的距离,来计算得到应该生成的小球个数,每次改变物体的位置,重新计算小球个数,少的小球,生成放到对应位置,多的小球销毁。该示例在X轴和Z轴正半轴组成的平面有效。
初次生成辅助线代码:
if (angle>90)
{
angle = 180 - angle;
num = Mathf.Floor(dis / 3);
for (int i = 0; i < num; i++)
{
float x = oriPoint.position.x - 3 * (i + 1) * Mathf.Cos(Mathf.Deg2Rad * angle);
float z = oriPoint.position.z + 3 * (i + 1) * Mathf.Sin(angle * Mathf.Deg2Rad);
GameObject obj = Instantiate(_prefab, new Vector3(x, 0, z), Quaternion.identity);
obj.transform.SetParent(_parent);
SubLineList.Add(obj);
}
}
else
{
num = Mathf.Floor(dis / 3);
for (int i = 0; i < num; i++)
{
float x = 3 * (i + 1) * Mathf.Cos(Mathf.Deg2Rad * angle) + oriPoint.position.x;
float z = 3 * (i + 1) * Mathf.Sin(angle * Mathf.Deg2Rad) + oriPoint.position.z;
GameObject obj = Instantiate(_prefab, new Vector3(x, 0, z), Quaternion.identity);
obj.transform.SetParent(_parent);
SubLineList.Add(obj);
}
}
目标移动后的处理:
if (num < Mathf.Floor(dis / 3))
{
float NowAngle= Vector3.Angle(endPoint.position - oriPoint.position, Vector3.right);
if (NowAngle>90)
{
NowAngle = 180 - NowAngle;
for (float i = num; i < Mathf.Floor(dis / 3); i++)
{
float x = oriPoint.position.x - 3 * (i + 1) * Mathf.Cos(Mathf.Deg2Rad * NowAngle);
float z = oriPoint.position.z + 3 * (i + 1) * Mathf.Sin(NowAngle * Mathf.Deg2Rad);
GameObject obj = Instantiate(_prefab, new Vector3(x, 0, z), Quaternion.identity);
obj.transform.SetParent(_parent);
SubLineList.Add(obj);
}
}
else
{
for (float i = num; i < Mathf.Floor(dis / 3); i++)
{
float x = 3 * (i + 1) * Mathf.Cos(Mathf.Deg2Rad * NowAngle) + oriPoint.position.x;
float z = 3 * (i + 1) * Mathf.Sin(NowAngle * Mathf.Deg2Rad) + oriPoint.position.z;
GameObject obj = Instantiate(_prefab, new Vector3(x, 0, z), Quaternion.identity);
obj.transform.SetParent(_parent);
SubLineList.Add(obj);
}
}
num = Mathf.Floor(dis / 3);
}
if (num > Mathf.Floor(dis / 3))
{
Debug.Log("Num:" + num + " Other:" + Mathf.Floor(dis / 3));
//销毁
for (int i = 0; i < num-Mathf.Floor(dis/3); i++)
{
Destroy(SubLineList[SubLineList.Count - 1]);
SubLineList.RemoveAt(SubLineList.Count - 1);
}
num = Mathf.Floor(dis / 3);
}
}