I am working on a top down game where the player can shoot bullets by aiming with his mouse. However, I am quite new to programming and am having a bit of trouble figuring out how to do so. My bullet prefab has this code on it:
public float speed;
public PlayerController player;
public GameObject enemyDeathEffect;
public GameObject impactEffect;
// Use this for initialization
void Start () {
player = FindObjectOfType<PlayerController> ();
if (player.transform.localScale.x < 0)
speed = -speed;
}
// Update is called once per frame
void Update () {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, speed);
}
void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Enemy") {
Destroy (other.gameObject);
//Instantiate (enemyDeathEffect, other.transform.position, other.transform.rotation);
}
//Instantiate(impactEffect, other.transform.position, other.transform.rotation);
if (other.name == "player") {
return;
}
Destroy (gameObject);
}
}
I instantiate the bullet using my player controller script. On it, I have a GameObject variable called firePoint, which is an empty GameObject situated at the center of my player sprite. I also have a GameObject variable in which I drag the prefab of my bullet for the player to access.
For now, the bullet goes upwards.
public Transform firePoint;
public GameObject friendlyBullet;
public bool hasGun;
public bool savedAnn;
public int memoriesCollected;
public bool nextToAnn;
public bool nextToMemory;
public bool memoryExists;
// Use this for initialization
void Start () {
playerBody = this.gameObject.GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
//go right
if (Input.GetKey (KeyCode.D)) {
playerBody.AddForce(new Vector2 (speed, 0));
//transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
}
//go left
if (Input.GetKey (KeyCode.A)){
playerBody.AddForce(new Vector2 (-speed, 0));
//transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
}
//go up
if (Input.GetKey (KeyCode.W)){
playerBody.AddForce(new Vector2 (0, speed));
//transform.position += new Vector3 (0.0f,speed * Time.deltaTime, 0.0f);
}
//go up
if (Input.GetKey (KeyCode.S)){
playerBody.AddForce(new Vector2 (0, -speed));
//transform.position -= new Vector3 (0.0f,speed * Time.deltaTime, 0.0f);
}
if (Input.GetKeyDown (KeyCode.Space) && (hasGun) ) {
Instantiate (friendlyBullet, firePoint.position, firePoint.rotation);
}
}
Any pointers as to where to integrate the mouse position would be greatly appreciated!