【问题标题】:Enemy attack the player?敌人攻击玩家?
【发布时间】:2014-10-26 11:18:12
【问题描述】:

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

我该怎么做?

我正在尝试这个。

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;
         }

     }
 }

【问题讨论】:

    标签: unity3d


    【解决方案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
    

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

    【讨论】:

    • shot.rigidbody2D.AddForce((player.position - shot.transform.position).magnitude * 500); 见:i.imgur.com/mxYxVcn.png
    • 我本来应该对向量进行归一化,这样力不依赖于距离,但我不小心写了magnitude而不是normalized
    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多