Problem with my firing script

I have a problem with my bullet once it fires. I have a script that checks for a bool if the player is facing left or not. And what I want to happen is that when the player faces the left direction and fires the bullet will go in the direction that he is facing. The script below is attached to the actual bullet and the bullet itself is the gameobject that checks for the bool. And it will work fine until I turn left the bullet would start to shake uncontrollably. What am I doing wrong here?

public float speed;

	public float death;
	

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(GameObject.Find("Player").GetComponent<PlayerMovement>().facingLeft)
		{
			speed = 1 * -speed;
		}
		transform.Translate(0, 0, Time.deltaTime * speed);
		StartCoroutine("DestroyBullet");

	}
	
	IEnumerator DestroyBullet()
	{
		yield return new WaitForSeconds(death);
		Destroy(gameObject);
	}

Instead of calling GameObject.Find("Player").GetComponent<PlayerMovement>() each frame, please declare additional variable, initialize it in Start or Awake and then use in Update.

Good point. I'm going to change that asap.

1 Answer

1

The problem is this: when the player is facing left, you’re changing the sign of speed each frame (positive to negative then back to positive etc).

Instead of modifying speed directly, you could declare a new variable inside Update() (for instance, “signedSpeed”). Set signedSpeed to equal speed, and negate it if the player is facing left. You can then pass signedSpeed in to your call to Translate().

Let us know if this solved your problem. If it did, please mark the answer as accepted.

Sorry about that. I haven't tried it yet but I know for a fact this shall work. Thanks for the info. I didn't think about that when I saw the bullet shaking back and forth. Thanks for your help.

Just tried what you said and it worked like I thought it would. Thanks for the help I'll definitely keep it in mind. Thanks again.

I'm glad it worked for you! Good luck on the rest of your game.