[英]Unity3D position Update when gameObject is changed
I am trying to make a vehicle changing game where there are 3 gameObject: car, tank and hover and if I press a button to change from car to a tank/hover i want them to be in a position where the car was.我正在尝试制作一个车辆更换游戏,其中有 3 个游戏对象:汽车、坦克和 hover,如果我按下按钮从汽车更改为坦克/悬停,我希望它们位于汽车所在的 position 中。
the z axis is forward z轴向前
I tried this code below but when I go backwards this will not work我在下面尝试了这段代码,但是当我向后 go 时,这将不起作用
UnityEngine;
public class Carswitcer : MonoBehaviour
{
public Transform car;
public Transform hover;
public Transform tank;
void Start()
{
car.gameObject.SetActive(true);
tank.gameObject.SetActive(false);
hover.gameObject.SetActive(false);
}
public void Car()
{
if (car.position.z < hover.position.z)
{
car.position = hover.position;
}
if (car.position.z < tank.position.z)
{
car.position = tank.position;
}
car.gameObject.SetActive(true);
tank.gameObject.SetActive(false);
hover.gameObject.SetActive(false);
}
public void Tank()
{
if (tank.position.z < hover.position.z)
{
tank.position = hover.position;
}
if (tank.position.z < car.position.z)
{
tank.position = car.position;
}
car.gameObject.SetActive(false);
tank.gameObject.SetActive(true);
hover.gameObject.SetActive(false);
}
public void Hover()
{
if (hover.position.z < car.position.z)
{
hover.position = car.position;
}
if (hover.position.z < tank.position.z)
{
hover.position = tank.position;
}
car.gameObject.SetActive(false);
tank.gameObject.SetActive(false);
hover.gameObject.SetActive(true);
}
Why compare the z
at all?为什么要比较
z
呢? Simply always copy the position of the currently active vehicle:只需始终复制当前活动车辆的 position:
public class Carswitcer : MonoBehaviour
{
public Transform car;
public Transform hover;
public Transform tank;
// Store the current vehicle
private Transform currentVehicle;
void Start()
{
tank.gameObject.SetActive(false);
hover.gameObject.SetActive(false);
SetActiveVehicle(car);
}
private void SetActiveVehicle(Transform newActiveVehicle)
{
// Is there a current vehicle?
if(currentVehicle)
{
// If so copy its position and set it inactive
newActiveVehicle.position = currentVehicle.position;
currentVehicle.gameObject.SetActive(false);
}
// Store the new active reference and set it active
currentVehicle = newActiveVehicle;
currentVehicle.gameObject.SetActive(true);
}
public void Car()
{
SetActiveVehicle(car);
}
public void Tank()
{
SetActiveVehicle(tank);
}
public void Hover()
{
SetActiveVehicle(hover);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.