导弹的方向很奇怪

时间:2018-11-13 14:47:53

标签: c# unity3d game-physics game-development

当我的飞船发射一些导弹摧毁敌人时,这是一种奇怪的行为。在某些情况下,导弹会“跳跃”并飞走。

当最近的敌人被一枚导弹摧毁而所有其他敌人都不再成为目标时,这似乎发生了。然后他们“跳跃”并飞走(离开屏幕)。

我仍然不知道这个问题的原因。

void Start () {
    rb = this.GetComponent<Rigidbody2D>();

    nearestEnemy = FindClosestTarget("EnemyShipTag");
}

获得最近的目标(敌人)

GameObject FindClosestTarget(string _target) {

    enemies = GameObject.FindGameObjectsWithTag(_target);

    closest = null;

    distance = Mathf.Infinity;

    _position = this.transform.position;

    foreach (GameObject enemy in enemies) {

        diff = enemy.transform.position - _position;

        curDistance = diff.sqrMagnitude;

        if (curDistance < distance) {
            closest = enemy;
            distance = curDistance;
        }
    }

return closest;

}

如果NearestEnemy不为空,则计算向最近敌人的移动

void FixedUpdate () {


    if (nearestEnemy != null) {//is enemy available?

        Vector2 enemyTarget = nearestEnemy.transform.position;
        Vector2 direction = (Vector2)enemyTarget - rb.position;

        direction.Normalize ();

        float rotateAmount = Vector3.Cross (direction, transform.up).z;

        rb.angularVelocity = -rotateAmount * rotateSpeed;

        float speed = 6f;

        float step = speed * Time.deltaTime;

        transform.position = Vector3.MoveTowards(transform.position, nearestEnemy.transform.position, step);

    } else {
        //rocket shall fly straight ahead if there's no target
        rb.velocity = transform.up * speed;
}

这些函数是EnemyControl.cs脚本的一部分

void OnTriggerEnter2D (Collider2D col) {//this function will trigger when there is a collision of our game objects
    //detect collision of the enemy ship with the player ship, or with a player's bullet
    if ((col.tag == "PlayerShipTag") || (col.tag == "MissileUpgradeTag")) {
    EnemyDestroyed ();
}

void EnemyDestroyed () {

Destroy (gameObject);//Destroy the enemy ship

        dead = true;

        PlayerControl.enemiesDestroyed++;


}

missile_direction

0 个答案:

没有答案