Hi, I’ve got a 2D sprite for a platformed that’s set to flip depending on input, as well as instantiating a bullet depending on which way he’s facing:
protected Animator animator;
bool run = false;
bool jump = false;
public Vector2 jumpForce = new Vector2(0, 400);
public bool facingRight = true; // For determining which way the player is currently facing.
public Transform bulletPrefab;
public float bulletOffset = 1;
public float fireRate = 5;
private float timeBetweenShots;
// Use this for initialization
void Start () {
timeBetweenShots = 1 / fireRate;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
rigidbody2D.velocity = new Vector2 (Input.GetAxis ("Horizontal") * 5, rigidbody2D.velocity.y);
if (Input.GetKeyUp ("space")) {
if (rigidbody2D.velocity.y == 0) {
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce (jumpForce);
}
}
if (Input.GetKey (KeyCode.F)) {
Fire ();
}
MoveCharacter ();
}
double nextFire;
private void Fire (){
// Logic to check when to fire
if (Time.time > nextFire)
{
nextFire = Time.time + timeBetweenShots;
// Create bullet and fire !
if(facingRight)
Instantiate(bulletPrefab, transform.position + transform.right * bulletOffset, transform.rotation);
else if(!facingRight)
Instantiate(bulletPrefab, transform.position + -transform.right * bulletOffset, transform.rotation);
}
}
void FixedUpdate ()
{
// Cache the horizontal input.
float h = Input.GetAxis("Horizontal");
// If the input is moving the player right and the player is facing left...
if(h > 0 && !facingRight)
// ... flip the player.
Flip();
// Otherwise if the input is moving the player left and the player is facing right...
else if(h < 0 && facingRight)
// ... flip the player.
Flip();
}
void Flip()
{
// Switch the way the player is labelled as facing.
facingRight = !facingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
My problem is that once the bullet is instantiated I can’t get it to travel left if the player is facing left (it always moves to the right). Here’s the bullet code:
public float bulletSpeed = 20;
public float timeToDie = 3;
float deathTime;
public bool facingRight = true;
public int scoreValue;
private GameController gameController;
// Use this for initialization
void Start () {
if (facingRight)
rigidbody2D.velocity = transform.right * bulletSpeed;
else if(!facingRight)
rigidbody2D.velocity = -transform.right * bulletSpeed;
deathTime = Time.time + timeToDie;
Any help please? Thanks!