Player's sprite flips when moving, but bullets shoot constantly right

Hi,

I am making a 2D platformer game (brand new at this whole thing!). My spirte flips left and right when moving, however I cannot get the projectile to shoot the same way, it always shoots right.

I have put all the code on the “player” so it shoots the projectile from there instead of putting the shooting mechanic on the bullet itself.

Here is my code for the player. Can anyone help me in saying what code needs to go where to make sure the bullet shoots the same way the player is facing?!?!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class Player : MonoBehaviour
{
// Config
[Header(“Movement”)]
[SerializeField] float runSpeed = 5f;
[SerializeField] float jumpSpeed = 5f;

[Header(“Projectile”)]
[SerializeField] GameObject bulletPrefab;
[SerializeField] GameObject gun;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float projectileFiringPeriod = 0.1f;

[Header(“Player FX”)]
[SerializeField] AudioClip playerShoot;
[SerializeField] [Range(0, 1)] float playerShootVolume = 0.7f;

Coroutine shootingCoroutine;

// state
bool isAlive = true;

// Cached Component References
Rigidbody2D myRigidBody;
Animator myAnimator;
PolygonCollider2D myBodyCollider;
BoxCollider2D myFeet;

//Message then methods
void Start()
{
myRigidBody = GetComponent();
myAnimator = GetComponent();
myBodyCollider = GetComponent();
myFeet = GetComponent();
}

// Update is called once per frame
void Update()
{
if (!isAlive) { return; }

Run();
FlipSprite();
Jump();
Die();
Shoot();
}

private void Run()
{
float controlThrow = CrossPlatformInputManager.GetAxis(“Horizontal”); // -1 to +1
Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
myRigidBody.velocity = playerVelocity;
Debug.Log(playerVelocity);

bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
myAnimator.SetBool(“Running”, playerHasHorizontalSpeed);
}

private void Jump()
{
if (!myFeet.IsTouchingLayers(LayerMask.GetMask(“Ground”))) { return; }

if (CrossPlatformInputManager.GetButtonDown(“Jump”))
{
Vector2 jumpVelocityToAdd = new Vector2(0f, jumpSpeed);
myRigidBody.velocity += jumpVelocityToAdd;
}
}

private void Die()
{
if (myBodyCollider.IsTouchingLayers(LayerMask.GetMask(“Enemy”, “Spikes”)))
{
isAlive = false;
myAnimator.SetTrigger(“Die”);
FindObjectOfType().ProcessPlayerDeath();
}
}

private void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);
}
}

private void Shoot()
{
if (Input.GetButtonDown(“Fire1”))
{
shootingCoroutine = StartCoroutine(ShootContinuously());
}
if (Input.GetButtonUp(“Fire1”))
{
StopCoroutine(shootingCoroutine);
}
}

IEnumerator ShootContinuously()
{
while (true)
{
GameObject ball = Instantiate(
bulletPrefab,
gun.transform.position,
Quaternion.identity) as GameObject;
ball.GetComponent().velocity = new Vector2(projectileSpeed, 0);
yield return new WaitForSeconds(projectileFiringPeriod);
AudioSource.PlayClipAtPoint(playerShoot, Camera.main.transform.position, playerShootVolume);
}
}
}

A massive thanks in advance if someone can help me. As I say, I’m brand new to coding, so have 0 clues what I’m doing lol.

Hey,

Please use the insert code button when trying to display code:


It makes the code much easier to read.

I looked over the code briefly, and it looks like the issue is that the “projectileSpeed” variable is initialized (starts at) a value of 10f and never changes. That’s why the bullet only goes to the right. You need a way to flip the ball velocity when you flip the sprite.

If you replace this line ball.GetComponent<Rigidbody2D>().velocity = new Vector2(projectileSpeed, 0); with this:

            if (transform.localScale.x > 0f)
            {
                ball.GetComponent<Rigidbody2D>().velocity = new Vector2(projectileSpeed, 0);
            }
            else
            {
                ball.GetComponent<Rigidbody2D>().velocity = new Vector2(-projectileSpeed, 0);
            }

It might work? I’m not actually going to test it, that would be a ton of work. The above code is located in the ShootContinuously() coroutine by the way.

If you got this code from somewhere (like a tutorial video), can you link me the source please?

1 Like

YOU ARE AN ABSOLUTE LEGEND!!!

Thank you so much, this works!!

I will definitely use the insert code button next time :slight_smile:

You see, I thought it had to go somewhere in ShootContinuously, but didn’t know how to write it or exactly what to replace, but your code did the trick, so I’ll definitely be adding your username to the game credits if you don’t mind?

As for my code. I have been doing a course on Udemy ( Complete C# Unity Game Developer 2D, by GameDevTV ).

I used different parts of code from different “games” within the course we learnt to make the player move and shoot. The shoot/health mechanics were actually from a “Block Breaker” section of the course, which is why the ball never had to be shot from another direction as it was always going on the Y axis. I simply just changed this to the X axis.

I just wanted to try and make a 2D game I can be proud of using free to use assets online, as a first attempt to show friends/family etc as I am looking into progressing onto different courses and tutorials to try and expand my learning.

Thank you again so much for your help, I really do appreciate it! (Let me know if you don’t want me to mention your username/name in the credits of the game, but if you’re happy for me to, because your code correction has helped me 100000% I feel it’s only right).

Adam

1 Like

Glad I could be of help!

I did that course too a while back, I think it’s really good. I was curious about the source of your code to see if it was copied correctly, but if you wrote everything yourself then that isn’t applicable. No code is perfect the first time it’s written, especially if we’re still learning.

By the way, nice job applying a bunch of the stuff you learned into your own game. It took me a while before I got the hang of coroutines and stuff like that haha.

As for crediting me, don’t worry about that. I like browsing the forums because it’s fun helping people out, and I often learn things while trying to solve issues.

Keep up the good work, take care!

Yea, it really was an amazing course, took me from knowing nothing to quite a bit in a short space of time!

Thank you, it was confusing, but I kept stringing different bits and pieces together until it worked which is cool. I do appreciate it, ill drop a link to the game once I’ve completed it on here for you to have a look at.

Thanks again, and take care :slight_smile:

1 Like