我试图按照本教程进行操作,并制作一个“太空侵略者”副本,但稍后可能会对其进行调整,使其具有更多的几何图形战争风格。
无论如何我同时在教自己C#和Unity,所以这是相当困难的,我理解大多数代码,但我却不懂,所以我相信挂断的地方...
该代码应该可以在屏幕上左右移动我的编队,但是经过数小时的尝试编辑我的代码并对其进行调整之后,我唯一注意到的是当我更改BoundaryLeftEdge和BoundaryRightEdge Vector 3时,会有不同的行为...但是它还是要么向左移动,然后向后移动第四点,除了它应该偏离屏幕外,或者它向右移动并被卡住,依此类推,等等……第四,我希望它从屏幕上向后移动第四点从A点到B点,但我似乎无法解决:(对不起,我是一个新手,自学比我想像的要难得多
using UnityEngine;
using System.Collections;
public class FormationController : MonoBehaviour
{ //Spawning Variables
public GameObject EnemyPrefab;
public float W = 10, H = 5;
//Movement Variables
public float Speed = 5;
private int Direction;
private float BoundaryRightEdge, BoundaryLeftEdge;
public float Padding = 0.25f;
void Start() //Setting Boundary
{
Camera camera = GameObject.Find("Player").GetComponentInChildren<Camera>();
float distance = camera.transform.position.z - camera.transform.position.z;
BoundaryLeftEdge = camera.ViewportToWorldPoint(new Vector3(0, 0, distance)).x + Padding;
BoundaryRightEdge = camera.ViewportToWorldPoint(new Vector3(1, 1, distance)).x - Padding;
}
void OnDrawGizmos()
{
float xmin, xmax, ymin, ymax;
xmin = transform.position.x - 0.5f * W;
xmax = transform.position.x + 0.5f * W;
ymin = transform.position.y - 0.5f * H;
ymax = transform.position.y + 0.5f * H;
Gizmos.DrawLine(new Vector3(xmin, ymin, 0), new Vector3(xmin, ymax));
Gizmos.DrawLine(new Vector3(xmin, ymax, 0), new Vector3(xmax, ymax));
Gizmos.DrawLine(new Vector3(xmax, ymax, 0), new Vector3(xmax, ymin));
Gizmos.DrawLine(new Vector3(xmax, ymin, 0), new Vector3(xmin, ymin));
}
void Update()
{
float formationRightEdge = transform.position.x + 0.5f * W;
float formationLeftEdge = transform.position.x - 0.5f * W;
if (formationRightEdge > BoundaryRightEdge)
{
Direction = -1;
}
if (formationLeftEdge < BoundaryLeftEdge)
{
Direction = 1;
}
transform.position += new Vector3(Direction * Speed * Time.deltaTime, 0, 0);
//Spawn Enemies on Keypress
if (Input.GetKeyDown(KeyCode.S))
{
foreach (Transform child in transform)
{
GameObject enemy = Instantiate(EnemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
}
}
`
最佳答案
根据您的代码,除非您在世界点上进行反向转换,否则我只能假定formationRightEdge
小于BoundaryLeftEdge
并且formationLeftEdge
应当大于BoundaryLeftEdge
。
尝试这个 -
if (formationRightEdge < BoundaryRightEdge)
{
Direction = -1;
}
if (formationLeftEdge > BoundaryLeftEdge)
{
Direction = 1;
}
也许您的
Direction = 1
和Direction = -1
应该颠倒。当然,请检查是否在检查器中为公共变量设置了不同的值。您可以在此处重置为默认值(在此脚本中定义)。