I have a top down shooter. The player can move in the primary 4 directions, and follows the mouse for rotation.
When I shoot, the bullets never leave the player, they just spawn on top of the player sprite.
I have tried a combination of velocity and AddForce methods, but I don't understand why the bullets never move. I have tried moving them in the Bullet's script or in the calling WeaponAttack script that Instantiates the Bullet.
Side note for educational purposes: Which method is better? Should the bullet govern its direction and velocity or should the Instantiating class govern it?
PLAYER ROTATION SCRIPT
public class RotateToDirection : MonoBehaviour {
Vector3 mousePos;
Camera cam;
Rigidbody2D rid;
void Awake () {
rid = this.GetComponent <Rigidbody2D> ();
cam = Camera.main;
}
void FixedUpdate () {
rotateToDirection ();
}
private void rotateToDirection() {
mousePos = cam.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z - cam.transform.position.z));
rid.transform.eulerAngles = new Vector3 (0, 0, Mathf.Atan2 ((mousePos.y - transform.position.y), (mousePos.x - transform.position.x)) * Mathf.Rad2Deg);
}
}
WEAPONATTACK (SHOOTS THE BULLET)
public class WeaponAttack : MonoBehaviour {
public GameObject bullet;
public GameObject player;
public float bulletSpeed;
void FixedUpdate () {
if(Input.GetMouseButton (0)){
attack ();
}
}
public void attack(){
Instantiate (bullet, player.transform.position, player.transform.rotation );
//Rigidbody2D bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0, 0, 1))) as Rigidbody2D;
//bulletInstance.velocity = transform.forward * bulletSpeed;
Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), player.GetComponent<Collider2D>());
}
}
BULLET
public class Bullet : MonoBehaviour {
public float moveSpeed = 500.0f;
private float killTime = 1.0f;
private Rigidbody2D body;
void Awake() {
body = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
killTime -= Time.deltaTime;
if (killTime <= 0) {
Destroy (this.gameObject);
} else {
body.position = body.position * moveSpeed * Time.deltaTime;
}
}
}