- Home /
GameObject instances affecting each other
I have a function in a script attached to the player object which fires a cannonball when the player hits space:
void Fire()
{
Object cannonBall = Resources.Load("cannonball");
GameObject shotInstance = (GameObject)Instantiate(cannonBall);
shotInstance.GetComponent<Rigidbody2D>().AddForce(new Vector2(Mathf.Cos(angle / 90f) * cannonForce, Mathf.Sin(angle / 90f) * cannonForce));
}
This works fine by itself, I can fire many cannonballs in rapid succession and they do not interact.
However, when I use nearly the same function in a different script attached to an enemy, it interacts with the player's shots.
void Fire()
{
var angle = 20.0f;
Object cannonBall = Resources.Load("cannonball");
GameObject shotInstance = (GameObject)Instantiate(cannonBall);
shotInstance.GetComponent<Rigidbody2D>().AddForce(new Vector2(-1 * Mathf.Cos(angle / 90f) * cannonForce, Mathf.Sin(angle / 90f) * cannonForce));
}
If the enemy's Fire() function is called after the player's Fire() function, it adds the force to both cannonballs. I find this very confusing as the player's cannonballs do not interact with each other. None of the objects are static. Can anyone tell me what I need to do here so that the enemy shots do not affect the player's?
Edit: the player cannon exists as an object on the scene, the enemy's is instantiated in the same way as the cannonball by an enemy loader script
Your answer
Follow this Question
Related Questions
Fireball instantiate - lags 1 Answer
Prefabs wont instantiate using a for loop? 1 Answer
Rotation problem with spawning bullet 2 Answers
Instantiate Reference Problem 1 Answer