我有2个游戏对象,一个是蓝色和红色。他们俩都在摄像机的限制下在场景中四处奔跑,因此他们无法通过某个区域。
如果可能的话,我也想知道如何在对角线上移动它们。
这是我的全部代码。
public Transform Objectup;
public Transform Objectdown;
public Transform Objectright;
public Transform Objectleft;
public DirectionGameObject direction;
public int speed = 2;
public enum DirectionGameObject
{
Right,
Left,
Up,
Down
}
// Start is called before the first frame update
void Start()
{
direction = SortdirectionGameObject(direction);
}
// Update is called once per frame
void Update()
{
Destroy();
if(direction == DirectionGameObject.Right)
{
transform.Translate(Vector3.right * Time.deltaTime * speed);
if(transform.position.x >= Objectright.position.x)
{
direction = SortdirectionGameObject(direction);
}
}
if(direction == DirectionGameObject.Left)
{
transform.Translate(Vector3.left * Time.deltaTime * speed);
if(transform.position.x <= Objectleft.position.x)
{
direction = SortdirectionGameObject(direction);
}
}
if(direction == DirectionGameObject.Up)
{
transform.Translate(Vector3.up * Time.deltaTime * speed);
if(transform.position.y >= Objectup.position.y)
{
direction = SortdirectionGameObject(direction);
}
}
if(direction == DirectionGameObject.Down)
{
transform.Translate(Vector3.down * Time.deltaTime * speed);
if(transform.position.y <= Objectdown.position.y)
{
direction = SortdirectionGameObject(direction);
}
}
}
private DirectionGameObject SortdirectionGameObject(DirectionGameObject maindirection)
{
DirectionGameObject directionSorted = maindirection;
do{
int newDirection = Random.Range((int)DirectionGameObject.Right, (int)DirectionGameObject.Down + 1);
directionSorted = (DirectionGameObject)newDirection;
} while (maindirection == directionSorted);
return directionSorted;
}
void Destroy()
{
Destroy(gameObject,120.0f);
}
当我按G和V时,我需要在控制台上显示它们的颜色和位置。
答案 0 :(得分:0)
我不知道是否有一种获取Gameobject材质颜色的方法,但是您可以将Gameobject命名为它具有的颜色,因为颜色是静态的并且不会改变,因此您可以使用Gameobject.name方法,对于找到其他可以使用transform.Lookat的游戏对象
答案 1 :(得分:0)
您要查找的GameObject的color属性位于Renderer组件的材质中。
可以通过以下方式引用它:
gameObject.GetComponent<Renderer>().material.color
为了获取GameObject的Renderer组件,您必须具有对它的引用,例如:
GameObject object1;
GameObject object2;
然后您可以像这样获取每个对象的颜色:
Color color1 = object1.GetComponent<Renderer>().material.color;
然后您可以像这样检查颜色的值:
if (color1 == Color.red){
// Do something
}
或者,如果您想在控制台上显示其颜色:
Debug.Log(color1);
颜色存储为4个浮点值,因此,如果要输出“颜色为红色”或“颜色为蓝色”,则需要进行等效检查,就像我上面提供的“ //做某事”注释一样