无限改变方向

时间:2014-10-24 19:49:06

标签: c# unity3d

我试图让敌人改变方向,当他接触到玩家时,但是当他接触到它时,它开始改变方向而不停止,像这样的gif:

Image (Epilepsy warning)

我的代码:

private int directionValue = 1;
public Vector2 speed = new Vector2((3/2), 0);
public Vector2 direction = new Vector2(-1, 0);
private Vector2 movement;

void Update()
{
    movement = new Vector2(
        speed.x * direction.x * directionValue,
        speed.y * direction.y);
}

void FixedUpdate()
{
    rigidbody2D.velocity = movement;
}

void OnCollisionEnter2D(Collision2D coll)
{
    foreach (string i in changeDir) {
        if (coll.gameObject.name == i) {
            transform.localScale = new Vector3(-1 * this.gameObject.transform.localScale.x, this.gameObject.transform.localScale.y, 1);
            directionValue *= -1;
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

正如Borgleader所提到的那样,问题是触摸持续的时间不止一帧,然后你来回设置方向。您可以找出远离播放器的方向,并在每次调用OnCollisionEnter2D时根据该方向设置方向。

    if(gameObject.transform.position.x > coll.gameObject.transform.position.x)
    {
        directionValue = 1;
    }
    else
    {
        directionValue = -1;
    }

或者您可以使用计时器

public  float hitWait = 0.1f;
private float lastHitTime = 0.0;

void OnCollisionEnter2D(Collision2D coll)
{
    foreach (string i in changeDir) {
        if (coll.gameObject.name == i) {
            transform.localScale = new Vector3(-1 * this.gameObject.transform.localScale.x, this.gameObject.transform.localScale.y, 1);
            float timeNow = Time.timeSinceLevelLoad;
            if(timeNow > lastHitTime + hitWait){
                lastHitTime = timeNow;
                directionValue *= -1;
                break;
            }
        }
    }
}