有没有更好的方法让对象自动移动



我正在使对象(在本例中为汽车(根据这样的时间点自动移动:

public Image car1_right;
public int k;
public float i;
public float j;
void Start()
{
k = 1;
i = 0f;
j = 0f;
car1_right.enabled = false;
}
void Update()
{
if (TimeManager.gametimeDecimal == 9.0m && k == 1)
{
car1_right.enabled = true;
InvokeRepeating("car_move_1", 0f, 0.05f);
k = 2;
}
if (TimeManager.gametimeDecimal == 23.0m && k == 2)
{
k = 1;
i = 0f;
j = 0f;
}
}
void car_move_1()
{
car1_right.transform.localPosition = new Vector3(-35.0f + i, 531f - j, 0);
i += 1.8f;
j += 0.85f;
}

问题是,要添加更多 2 辆汽车,我必须为每个汽车再创建 3 个变量(这将是 6 辆(并将代码一式三份。

你知道更好的方法吗?

public struct Position
{            
public double X { get; set; } 
public double Y { get; set; }
}
public class Car
{
public bool IsEnabled { get; set; }
public Position Position { get; private set; }
public bool IsInMotion { get; set; }
public void MoveCar(Position position)
{
if (IsEnabled && !IsInMotion)
{
Position = position;
}
}
}
class CarSimulator
{
List<Car> cars = new List<Car>(); // populate it
void MoveAllCars()
{
foreach (var car in cars)
{
car.MoveCar(GetPosition());
}
}
}

它可能看起来像这样。您将决定需要实现的逻辑。

最新更新