- Home /
 
Shooting script C#
I'm trying to make a shooting script for my 2D game, but it's not working. If the mousePos.x < playerPos.x the bullets just switch direction. I understand why this is happening, but I cannot find a fix. How can I make is so the bullets spawn with an initial unchanged speed and direction?
  using UnityEngine;
  using System.Collections;
  
  public class bulletScript : MonoBehaviour {
  
      public float bulletSpeed = 100f;
      private Vector2 mousePos;
      private Vector3 playerPos;
      public GameObject bullet;
  
      // Use this for initialization
      void Start () {
  
      }
  
      // Update is called once per frame
      void Update () {
  
          if (Input.GetMouseButtonDown(0)) {
              Instantiate (bullet, playerPos, Quaternion.identity);
          }
  
          if (mousePos.x > playerPos.x) {
              transform.position += Vector3.right * Time.deltaTime * bulletSpeed;
          } 
  
          if (mousePos.x < playerPos.x)
          {
              transform.position += Vector3.left * Time.deltaTime * bulletSpeed;
          }
  
          mousePos = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
          playerPos = GameObject.Find ("squiddy").transform.position;
  
      }
  }
 
              Answer by Havax · Dec 15, 2016 at 09:45 AM
For starters, you're searching for your player gameobject every frame. Put "player = GameObject.Find("squiddy");" in the start function of your game, and update it's position in the beginning of the update function like so: "playerPos = player.transform.position;". In your script, your using "transform.position" which means your targetting the transform the script is attached to, but your instantiating the bullet GameObject and trying to effect that. "bullet.transform.position += Vector3.left Time.deltaTime bulletSpeed;"
Your answer