【发布时间】:2015-04-26 19:26:53
【问题描述】:
我正在尝试按照本教程制作一个 Space Invaders 副本,但我可能稍后会对其进行调整,使其更具几何战争风格。
无论如何,我同时自学 C# 和 Unity,所以这相当困难,我了解大部分代码,但有些我不明白,这就是我相信挂断的地方...
该代码应该在屏幕上左右移动我的编队,但经过数小时尝试编辑我的代码并对其进行调整后,我唯一注意到的是当我更改 BoundaryLeftEdge 和BoundaryRightEdge Vector 3 有不同的行为......但它仍然向左移动并像它应该的那样向后和第四个移动,除了它像从屏幕偏移或向右移动并卡住依此类推,第四……我希望它从 A 点向后移动到第四点,但我似乎无法做到这一点:(对不起,我是一个需要帮助的菜鸟,自学比我想象的要困难得多猜测
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;
}
}
}
} `
【问题讨论】: