First and foremost, I know this has been posted about a lot, but I’ve been reading through threads for more than an hour, and none of the solutions seem to be working. There’s obviously something in my code that I’m not seeing.
Anyway, I’m making a 2D platformer where the player and enemies can shoot bullets. I have a bullet prefab, and I’m spawning in bullets with GameObject.Instantiate() in a script attached to the prefab called Bullet.cs, which is a MonoBehavior. The bullet prefab has a rigidbody attached which is not kinematic. When the bullet object is created, it’s given a movement speed, which is applied in update() with AddForce(). The bullet spawns successfully, but it doesn’t move.
My structure: Player.cs is a MonoBehavior attached to the player that calls a method spawnBullet() in update(). bulletSpeed is a public float in Player.cs. spawnBullet() calls a public method in Bullet.cs which instantiates the bullet object. That bullet object then applies force in its update() method.
The relevant code from Player.cs:
public float shootSpeed;
public float shootDamage;
public int maxBulletCooldown;
void update () {
if (Input.GetKey ("space")) {
int direction = 0;
if (facingForward)
direction = 1;
else
direction = 3;
spawnBullet (shootSpeed, shootDamage, direction);
}
public void spawnBullet (float speed, float damage, int direction) {
if (bulletCooldown == 0) {
Bullet.initializeBullet (bulletPrefab, speed, damage, direction, transform.position + calculateOffset(direction));
bulletCooldown = maxBulletCooldown;
} else {
bulletCooldown--;
}
}
The relevant code from Bullet.cs:
private GameObject bullet;
private float speed;
private float damage;
private int direction;
void update () {
if (direction == 1)
transform.GetComponent <Rigidbody> ().AddForce (new Vector3 (speed, 0, 0));
else if (direction == 2)
transform.GetComponent <Rigidbody> ().AddForce (new Vector3 (0, speed, 0));
else if (direction == 3)
transform.GetComponent <Rigidbody> ().AddForce (new Vector3 (-speed, 0, 0));
else
transform.GetComponent <Rigidbody> ().AddForce (new Vector3 (0, -speed, 0));
}
//Direction: right = 1, down = 2, left = 3, up = 4
public static GameObject initializeBullet (Transform prefab, float speed, float damage, int orientation, Vector3 position) {
Transform bulletTransform = (Transform) GameObject.Instantiate (prefab, position, Quaternion.identity);
bulletTransform.gameObject.AddComponent <Bullet> ();
Bullet bullet = bulletTransform.GetComponent<Bullet> ();
bullet.setDamage (damage);
bullet.setSpeed (speed);
bullet.setOrientation (orientation);
return bulletTransform.gameObject;
}
Anyone know what I’m not seeing here?