- Home /
2D character not shooting in correct direction
hello, I'm making a simple mobile platformer. My character is flipping directions correctly but the spawned bullets don't travel in flipped direction and instead always go on the right side. Code for flipping my character:
void flip()
{
facR = !facR;
transform.Rotate(0f, 180f, 0f);
}
Shoot script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shoot : MonoBehaviour
{
public GameObject bullet;
public Transform point;
public void shootB()
{
Instantiate(bullet, point.position, point.rotation);
}
}
bullet instantiate:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletscrp : MonoBehaviour
{
public Rigidbody2D rb;
public float speed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed, rb.velocity.y);
}
}
Inspector window and hierarchy:
Pls help!
Answer by Morphosys · May 12, 2020 at 10:26 AM
Hi, the problem you describe is pretty easy to fix, one of the ways to do that is the following one :
In your bullet prefab, replace your bullet script with one that contains :
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 10f;
public Rigidbody2D rbody;
void Start()
{
rbody.velocity = speed * transform.right;
}
}
Here you are multiplying the speed (that is adjustable in your inspector) with the transform.right, allowing your character to shoot in the "right" axis with both positive and negative values.
(Edit 12 May 2020 at 12:30) : Was your shootpoint rotating too ? If so everything should work, if not I have a solution for that.
Wow! It fixed it. But why transform.forward didn't work tho. But thanks a lot
Hi!
Just for clarification - transform.forward is direction that pointing in z direction of the object. In 3D it will be front direction, but in 2D it's going to be direction into the screen, so transform.forward wouldn't work here, but you also didn't implement it.
Look at your bullet code:
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed, rb.velocity.y);
}
The thing is that you always applied to the bullet positive speed value along X axis what means no matter what your object rotation is it will go towards same direction, because you didn't multiply your speed variable as xKarter implemented it in the answer that worked for you.
I hope that makes more clear why the answer fixed it for you and why it did not work previosly x)
Oh! Thanks for the explanation. It really helped me :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612234025im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Bullet only firing in 1 direction. 1 Answer
How would I add force/ burst fire to my gun? 2 Answers
How to get bullets to hit crosshair 2 Answers