Home > Back-end >  Unity2D - Enemy shoot at player in a cone shaped pattern
Unity2D - Enemy shoot at player in a cone shaped pattern

Time:08-27

I am trying to set up an enemy that will shoot at the player in a cone shape/shotgun shape. If I set the projectile script to transform.position = transform.right * m_Speed * Time.deltaTime; then the cone shape works as intended, just only to the right and not in the direction of the player. With the current setup (below), the projectile will shoot at the player, but all the bullet prefabs will be on top of each other and all going in the same direction, not in a cone shape.

How can I adjust this so the enemy will shoot at the player but retain the cone shape?

Enemy Script

    aimAngle = 60f;
    for (int i = 0; i < spreadShot; i  )
    {
        var shotRotation = gameObject.transform.rotation;
        shotRotation *= Quaternion.Euler(0, 0, aimAngle);

        GameObject clone = Instantiate(projectile, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), shotRotation);
        aimAngle = aimAngle - 30f;

        Vector3 direction = (Vector3)((player.transform.position - transform.position));
        direction.Normalize();

        clone.GetComponent<Projectile>().Setup(direction);
    }

Projectile.cs

[SerializeField] float m_Speed;
Vector3 shootDir;

public void Setup(Vector3 shootDir)
{
    this.shootDir = shootDir;
}

private void Update() 
{
    transform.position  = shootDir * m_Speed * Time.deltaTime;
}

CodePudding user response:

At the moment, your code rotates the bullet itself, not the vector of direction towards player. Shot rotation you computed doesn't affect your direction in any way.

To elaborate, if you rotate an object and just move it by transform.position, you changed its position by exactly how you specified, as if you just changed its x, y or z component by hand. Your rotation change to an object would produce desired results if you used transform.Translate(params) as this operation is dependant on object's current rotation and scale.

Apply your rotation to the direction, it should work just fine :)

More reference on how to do it: https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html

  • Related