im making a 3d sidescroller game. i watched a brackeys video on 2d shooting but that didnt work. i could shoot to the right but right only. if i faced left, i would still shoot to the right. then i made another project and this time i could still shoot to the right but when i faced left no bullet would instantiate at all. then i tried to do something myself. i have a player movement script called “playerMovement” and a script for the bullet called “bulletScript” basically i made a boolean to check if player was facing left and i would make the bullet go left or right according to that boolean.
the script on the bullet prefab:
public class bulletScript : MonoBehaviour
{
public Rigidbody rb;
public float bulletSpeed;
playerMovement player_script;
Transform player;
private void Awake()
{
player = GameObject.Find("Player").transform;
player_script = GameObject.Find("Player").GetComponent<playerMovement>();
}
// Start is called before the first frame update
void Start()
{
if (player_script.isFacingLeft ==false)
{
rb.velocity = Vector3.right;
}
else
{
rb.velocity = Vector3.left;
}
}
the script on the player :
public class playerMovement : MonoBehaviour
{
public float moveSpeed;
public Rigidbody rb;
public int jumpForce;
public bool isGrounded = true;
public bool isFacingLeft = false;
public GameObject gunPoint;
public GameObject bullet;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.D) && !isFacingLeft)
{
//transform.Translate(new Vector3(1f, 0f, 0f) * moveSpeed * Time.deltaTime);
rb.velocity = new Vector3(moveSpeed, rb.velocity.y, rb.velocity.z);
}else if (Input.GetKey(KeyCode.D) && isFacingLeft)
{
rb.velocity = new Vector3(moveSpeed, rb.velocity.y, rb.velocity.z);
isFacingLeft = false;
Flip();
}else if (Input.GetKey(KeyCode.A) && !isFacingLeft)
{
isFacingLeft = true;
Flip();
}
else if (Input.GetKey(KeyCode.A) && isFacingLeft)
{
//transform.Translate(new Vector3(-1f, 0f, 0f) * moveSpeed * Time.deltaTime);
rb.velocity = new Vector3(-moveSpeed, rb.velocity.y, rb.velocity.z);
}
if (Input.GetKeyDown(KeyCode.W) && isGrounded)
{
isGrounded = false;
rb.AddForce(Vector3.up * jumpForce * Time.fixedDeltaTime);
}
if (Input.GetKeyDown(KeyCode.Space) && !isFacingLeft)
{
Instantiate(bullet , gunPoint.transform.position, Quaternion.identity);
}
}
private void Flip()
{
gameObject.transform.Rotate(0f, 180f, 0f);
gunPoint.transform.Rotate(0f, 180f, 0f);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "ground")
{
isGrounded = true;
}
}
}