- Home /
How to make 3 bullets fire at different angles
So I'm trying to make a enemy that will fire 3 bullets going in 3 different directions based on where the player is, sort of like how a 2d space shooter would do it. Example drawing :
Would I change the quaternion.identity or would I change what moveDirection means? How would I go about doing this, any help is thanked! Here is what I've got so far.
Code On Prefab: { public float moveSpeed; public float lifeTimeWeb; public int damage;
Rigidbody2D rb;
Player target;
Vector2 moveDirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
target = GameObject.FindObjectOfType<Player>();
moveDirection = (target.transform.position - transform.position).normalized * moveSpeed;
rb.velocity = new Vector2(moveDirection.x, moveDirection.y);
Destroy(gameObject, lifeTimeWeb);
}
void OnTriggerEnter2D (Collider2D collision)
{
//Other Code
}
}
Enemy Bullet Code:
public Transform shootPoint;
public GameObject bullet;
public void CheckIfTimeToFire()
{
if (Time.time > nextFire){
anim.SetTrigger("attack");
Instantiate(bullet, shootPoint.position, Quaternion.identity);
nextFire = Time.time + fireRate;
}
}
Answer by diego-giacomelli · Nov 02, 2020 at 12:24 PM
You will need to get the direction that bullet should be fired:
player.transform.position - transform.position;
Then you need to rotate it by the angle you want to fire the bullet:
var direction = Quaternion.Euler(0, 0, angle) * (target - transform.position);
After that, you need to sum the bullet's current position with the direction.
_targetPosition = transform.position + direction;
In the Bullet's Update method you can use something like this:
transform.position = Vector2.Lerp(transform.position, _targetPosition, Time.deltaTime * Speed);
I uploaded a .unitypackage with the sample used in the .gif, you can import it in any Unity 2D project and test it sample scene. The player ship can be moved using arrows keys.
Hello, thank you so much, this is probably the best help that I could of gotten. Working great!
Hi @diego-giacomelli , the file "sampleunitypackage" doesn't seems longer avaible.Could you re-upload it again? And does this code works when the the enemy in this case moves? In my case the further I'm from the Origin of the World space the less precision it have. Thanks.