C# 让物体在统一中前后移动?
我最近开始学习c#和unity,我们应该做一个游戏,一个球在迷宫中滚动,有被敌人摧毁的危险,当你到达终点时会弹出一条信息。我已经完成了大部分工作;然而,我的敌人,他们被认为是来回移动和破坏球时,接触,不工作。当游戏开始时,墙壁和地板会爆炸,我甚至不确定它们是否有效。在我们当前的任务中,我们必须添加类和另一个玩家(我很确定我已经知道怎么做了)。这是我敌人职业的当前代码:C# 让物体在统一中前后移动?,c#,unity3d,C#,Unity3d,我最近开始学习c#和unity,我们应该做一个游戏,一个球在迷宫中滚动,有被敌人摧毁的危险,当你到达终点时会弹出一条信息。我已经完成了大部分工作;然而,我的敌人,他们被认为是来回移动和破坏球时,接触,不工作。当游戏开始时,墙壁和地板会爆炸,我甚至不确定它们是否有效。在我们当前的任务中,我们必须添加类和另一个玩家(我很确定我已经知道怎么做了)。这是我敌人职业的当前代码: using UnityEngine; using System; [System.Serializable] public 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)中,有一些我完全不理解的错误。如果你们知道如何修复它,或者知道更好的方法来做某事,或者至少知道更好的方法来来回移动物体,请让我知道
非常感谢您花时间回答这个问题 出现错误的原因有两个,但都很简单 第一个错误,在第21行
(xAxis=Boundary)
,您得到一个错误,因为您将类型的值Boundary
分配给类型的变量向量3
这就像试图说一个苹果等于一个橘子(他们没有)
在C#等语言中,赋值的左手和右手的类型必须相同
简而言之
类型变量=值;-->仅当LHS的类型为RHS的类型时有效
发生第二个错误是因为您试图使用错误的值集创建
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);
}
}
xAxis是一个矢量3,而Boundary不是,所以您不应该指定xAxis=Boundary代码>我建议您首先成功完成本教程,然后您可以添加移动敌人的新逻辑:我已经完成了滚动球教程,但方块是以固定方式来回移动的方块。我试过打乒乓球,但那只起了部分作用。