敌人攻击玩家?

时间:2014-10-26 11:18:13

标签: unity3d

我创造了一个攻击玩家的敌人,这个敌人有一把枪。我希望当这把枪射击时,射击朝着玩家的方向发展。我可以实例化,但不能改变方向子弹来攻击我的位置。

我该怎么做?

我正在尝试这个。

public class EnemyShotGun : MonoBehaviour {

     public GameObject[] gun; //gun attack player
     public GameObject prefabShot; //shot
     public float enemyShotSpeed;
     private float delayAttack; 
     public float timeAttack; 

     //player
     private Transform player;

     // Use this for initialization
     void Start () {
         player = GameObject.FindGameObjectWithTag("AirPlane").transform;
     }

     // Update is called once per frame
     void Update () {
         delayAttack += Time.deltaTime;
         if (delayAttack >= timeAttack){            
             for(int x = 0; x < gun.Length; x++){
                 GameObject shot = Instantiate(prefabShot, gun[x].transform.position, Quaternion.identity) as GameObject;
                 shot.rigidbody2D.AddRelativeForce(new Vector2(0, -500)); 
                 shot.transform.position = player.position; //bullet goes to player position
             }                        
             delayAttack = 0;
         }

     }
 }

1 个答案:

答案 0 :(得分:1)

你需要做的是为玩家增加力量。不朝着-Y方向。所以改变这个:

             shot.rigidbody2D.AddForce(new Vector2(0, -500));

这样的事情:

             shot.rigidbody2D.AddForce(((Vector2)(player.position - shot.transform.position)).normalized * 500);

其中player.position - shot.transform.position是从镜头到玩家的向量。

也删除此行:

             shot.transform.position = player.position; //bullet goes to player position

它立即将镜头移动到玩家位置。