让物体在统一中来回移动?

时间:2016-04-03 23:32:52

标签: c# unity3d

我最近开始学习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行(xAxis = Boundary;)和第26行(transform.position = new Vector 3)中,有些错误我完全不理解。如果你们知道如何解决它或者知道更好的办法,或者至少是一种更好的方式来回移动物体,请告诉我!

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

1 个答案:

答案 0 :(得分:0)

您出于两个原因而收到错误,但相当微不足道。

第一个错误,在第21行(xAxis = Boundary)上,您收到了错误,因为您正在为变量指定类型 Boundary的值类型 Vector3

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

在C#等语言中,作业的左手和右手的类型必须相同。

简单地说

类型 变量 = ; - >仅适用于来自RHS的LHS = 类型 类型


您发生的第二个错误是因为您尝试使用错误的值集创建Vector3。创建类型的过程是通过调用您尝试创建的类的Constructor来完成的。

现在,看看Constructor for a Vector3。一个构造函数接受3个float类型的参数,另一个构造函数接受2个参数,类型为float
您尝试使用Vector3(来自Mathf.PingPong)和float(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);
    }
}
相关问题