我怎样才能让物体在unity2D中沿着那条路径移动?
how can i make the object move on that path in unity2D?
我希望我的敌人在这张照片中像这样移动。我怎样才能在 unity 2d 中实现这一点。
有很多方法可以实现这一点。一个好的起点是状态机。
- 你有一个状态决定你当前移动的方向。
- 在一定时间(或满足条件)后,您更改状态。
示例代码:
{
private int state = 1; // 1 means moving down and right, 2 means moving up.
// you could also use an enum for this.
private float time = 0; // how long the enemy is already moving in this direction
void Update() {
if (state == 1) {
// move down right
transform.position = transform.position + new Vector(1,-1,0) * Time.deltaTime;
} else if (state == 2) {
// move up
// TODO
}
// Add additional states here...
time += Time.deltaTime; // track how long you are in this state
// Change the condition here...
if (time > TIME_MOVING_IN_SAME_DIRECTION) {
time = 0; // reset time
// set next state:
if (state == 1) state = 2;
else if (state == 2) state = 1;
// Add additional changes between the states here if necessary
}
}
}
我希望我的敌人在这张照片中像这样移动。我怎样才能在 unity 2d 中实现这一点。
有很多方法可以实现这一点。一个好的起点是状态机。
- 你有一个状态决定你当前移动的方向。
- 在一定时间(或满足条件)后,您更改状态。
示例代码:
{
private int state = 1; // 1 means moving down and right, 2 means moving up.
// you could also use an enum for this.
private float time = 0; // how long the enemy is already moving in this direction
void Update() {
if (state == 1) {
// move down right
transform.position = transform.position + new Vector(1,-1,0) * Time.deltaTime;
} else if (state == 2) {
// move up
// TODO
}
// Add additional states here...
time += Time.deltaTime; // track how long you are in this state
// Change the condition here...
if (time > TIME_MOVING_IN_SAME_DIRECTION) {
time = 0; // reset time
// set next state:
if (state == 1) state = 2;
else if (state == 2) state = 1;
// Add additional changes between the states here if necessary
}
}
}