我正在尝试按照本教程制作一个太空入侵者复制品,但我可能稍后会对其进行调整,使其更具几何 war 风格。
我同时自学 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
应该颠倒过来。当然,检查您是否在检查器中为公共(public)变量设置了不同的值。您可以在那里重置为默认值(在此脚本中定义)。
关于c# - Unity ViewtoWorldPoint 不工作,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882416/