如何以某种方式移动角色?

时间:2018-07-23 17:37:58

标签: unity3d

有一种方法。角色从中点开始。然后,如果[{"name":"cat1"}] ,它应该向右移动,如果HorizontalAxis > 0,它应该向左移动。我做了这样的事情-

方式:

way image

< 0

数组的长度-3个元素。 从中间点到右边,字符通常同时向左和向右移动,但是一旦我到达最后一点,就会发生错误-

  

数组索引超出范围

在错误变量期间:

NeedPoint:-1;

CurrnetPoint:2;

从中间到左侧,该字符完全不显示。

1 个答案:

答案 0 :(得分:4)

这是解决方案:

  

字符从中点开始。然后它应该移动到   如果Horizo​​ntalAxis> 0,则为右侧;如果<0,则为左侧。

我假设“向右移动”意味着增加数组的索引,而“向左移动”意味着减少数组的索引

public Transform[] PatrolPoints;
public int NextPointOnLeft = 0; // because player starts at 1
public int NextPointOnRight = 2; // because player starts at 1

if (HorizontalAxis < 0)
{
    if (transform.position == PatrolPoints[NextPointOnLeft].position)
    {
        if(NextPointOnLeft > 0)
        {
            --NextPointOnLeft;
        }
        // EDIT: NextPointOnRight = NextPointOnLeft + 1;
    }
    // EDIT:
    NextPointOnRight = NextPointOnLeft + 1;
    transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NextPointOnLeft].position, moveRate * Time.deltaTime);
}
if (HorizontalAxis > 0)
{
    if (transform.position == PatrolPoints[NextPointOnRight].position)
    {
        if(NextPointOnRight < PatrolPoints.Length-1)
        {
            ++NextPointOnRight;
        }
        // EDIT: NextPointOnLeft = NextPointOnRight - 1;
    }
    // EDIT:
    NextPointOnLeft = NextPointOnRight - 1;
    transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NextPointOnRight].position, moveRate * Time.deltaTime);
}

如果您需要其他解决方案,请指定所需的内容