如何让敌人在 unity 2d 中射击玩家

时间:2021-07-12 20:09:59

标签: unity3d 2d

到目前为止敌人可以跟随玩家并且可以将枪指向玩家。我现在唯一需要做的就是让敌人向玩家射击。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{

    public GameObject player;
    public GameObject gun;

    void Update()
    {
        Vector3 difference = player.transform.position - gun.transform.position;
        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        gun.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);

    }
}

1 个答案:

答案 0 :(得分:1)

根据您是要使用可移动的子弹还是只是“我指向他受到伤害”,有两种方法。

第一种方式

因此,您必须创建一个 Bulletprefab 和一些应该生成它的位置。不,当你的敌人面对它可以射击的玩家时(最好有炮弹)。因此,您可以实例化子弹预制件,然后向子弹添加力。这可能看起来像这样:

// Some Attribute
public float fireRate = 0.5f;
private float nextFire = 0.0f;

// In Update
if(Time.time > nextFire) {
    if(!Bullet)
        return;
    nextFire = Time.time + fireRate;
    GameObject clone = Instantiate(Bullet, ShootPoint.position,ShootPoint.rotation);
    Rigidbody rb = clone.GetComponent<Rigidbody>();
    rb.AddRelativeForce(Vector3.forward * bulletSpeed, ForceMode.Impulse);
}

现在,您还可以像手榴弹一样将子弹稍微向上射击,或者将其刚体的重力设置为假,使其直线飞行。 Here 拍摄教程。

第二种方式

您可以使用 Raycasts 直接射击并检测您击中的物体。如果它确实击中了玩家,则对其造成伤害。就这么简单

Raycast