2016-04-03 55 views
0

我最近开始学习c#和团结,我们应该做一个游戏,一个球在迷宫中滚动,有被敌人摧毁的危险,并且当你到达最后时会弹出一个消息。我完成了大部分工作;然而,我的敌人,应该来回移动和触摸时摧毁球,不工作。游戏开始时,墙壁和地板会爆炸,我甚至不确定它们是否可以工作。在我们目前的任务中,我们必须添加类并添加另一个球员(我确信我已经知道如何去做)。这是我对目前我的敌人类代码:获取对象来回移动?

using UnityEngine; 
using System; 

[System.Serializable] 
public class Boundary 
{ 
    public float xMin, xMax; 
} 

public class BadGuyMovement : MonoBehaviour 


{ 
    public Transform transformx; 
    private Vector3 xAxis; 
    private float secondsForOneLength = 1f; 
    public Boundary boundary; 

    void Start() 
    { 
     xAxis = Boundary; 
    } 

    void Update() 
    { 
     transform.position = new Vector3(Mathf.PingPong(Time.time, 3), xAxis); 
    } 
    void OnTriggerEnter(Collider Player) 
    { 
     Destroy(Player.gameObject); 
    } 
} 

上线21(x轴=边界)和26(transform.position =新的Vector 3)有,我只是完全不理解的错误。如果你们知道如何解决这个问题,或者知道一个更好的方法来做某件事,或者至少有一个更好的方法来回移动一个物体,请让我知道!

非常感谢您花时间回答这个问题!

+1

X轴是的Vector3而边界是没有,所以你不应该指定'x轴=边界;' –

+0

我建议你就成功完成本教程,那么你可以添加可移动的敌人的新逻辑:[教程] (HTTP:// unity3d。com/learn/tutorials/projects/roll-ball-tutorial) –

+0

我已经做过滚球教程,但是正方形是以固定方式来回移动的。我尝试过乒乓球,但这只是部分帮助。 –

回答

0

由于两个原因,您会遇到错误,但相当平凡。

的第一个错误,第21行(xAxis = Boundary),你是因为你指定Boundary的价值Vector3的变量得到一个错误。

这就像试图说苹果等于橙色(他们没有)。

在像C#这样的语言中,赋值的左侧和右侧的类型必须相同。

简而言之

类型可变 = ; - >从LHS = 从RHS


你的第二个错误是发生仅在进行是因为你想创建一个错误的设定值的Vector3 。创建类型的过程是通过调用您要创建的类的Constructor完成的。

现在,看看Constructor for a Vector3。一个构造函数需要3个参数,类型为float,另一个需要2个参数,类型为float
您正尝试使用float(来自Mathf.PingPong)和Vector3(xAxis)调用Vector3的构造函数。

现在我们已经完成了,试试这段代码。

using UnityEngine; 
using System; 
[System.Serializable] 
public class Boundary 
{ 
    public float xMin, xMax; 
} 

public class BadGuyMovement : MonoBehaviour 
{ 
    public Transform transformx; 
    private Vector3 xAxis; 
    private float secondsForOneLength = 1f; 
    public Boundary boundary; //Assuming that you're assigning this value in the inspector 

    void Start() 
    { 
     //xAxis = Boundary; //This won't work. Apples != Oranges. 

    } 

    void Update() 
    { 
     //transform.position = new Vector3(Mathf.PingPong(Time.time, 3), xAxis); //Won't work, incorrect constructor for a Vector3 
     //The correct constructor will take either 2 float (x & y), or 3 floats (x, y & z). Let's ping pong the guy along the X-axis, i.e. change the value of X, and keep the values of Y & Z constant.    
     transform.position = new Vector3(Mathf.PingPong(boundary.xMin, boundary.xMax), transform.position.y, transform.position.z); 
    } 
    void OnTriggerEnter(Collider Player) 
    { 
     Destroy(Player.gameObject); 
    } 
}