- Home /
Instantiate bullet towards Player position
I've been working in a side scrolling shooter and everything is working great so far but I wanted to add some more variety to the way enemies attack the player, happens that the enemy shoot straight forward so is easy just to stay away from the bullet trajectory so my question is how can I make an enemy instantiate a bullet towards wherever the player's position is at that given frame? PS: The following Script is the enemy shooting behavior. Thanks in advance.
public GameObject bullet;
public Transform bulletPoint;
public float shotsPerSeconds;
public float shotDelay;
private float shotCounter;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float probability = Time.deltaTime * shotsPerSeconds;
if(Random.value < probability){
Fire();
}
}
void Fire(){
Instantiate(bullet, bulletPoint.position, bulletPoint.rotation);
}
}
Answer by TheSOULDev · Jul 29, 2017 at 11:15 PM
Add velocity to the bullet that is equal to a set positive constant * (Vector of player position - Vector of bullet spawn position). The constant will alter how fast your bullet flies, while the difference between the two vectors is a resulting vector going from the gun to the player. Make sure that you only do this on the frame the bullet is shot, otherwise it's going to accelerate and home onto the player.
So, in your implementation, I guess this would be something like:
void Fire()
{
Instantiate(bullet, bulletPoint.position, bulletPoint.rotation);
bullet.velocity = (player.position - bullet.position).normalized * constant;
}
This is assuming that player is a reference to your player game object which you have to reference somewhere in your script. Also note that the constant has to be any number > 0 for your bullet to move in the correct direction. The reason you normalize the vector is because you don't want the velocity to be dependent on the distance.
Also, I'm assuming the bullet has a rigidbody component on it. This is necessary for velocity to work.
This works great! Thanks for the explanation. @TheSOULDev
Your answer
Follow this Question
Related Questions
player goes crazy when using this, help! 0 Answers
instantiate prefabs y+1 from last instintiated prefab 1 Answer
How to determine the direction of an object to the player. 1 Answer
Instatiating a prefab in a random position 0 Answers
Strange shifting when reseting player position to origin 1 Answer