0
votes

I am doing a 2d game and the movement and action it's based on buttons on the screen . My bullets when I shoot are just going to the left never to the right , even if a pressed my player to walk to the right( the game is made in unity 2d) How can I make the bullet to detect the tag enemy?

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

public class Character : MonoBehaviour
{

    Rigidbody2D rb;
    float dirX;

    [SerializeField]
    float moveSpeed = 5f, jumpForce = 600f, bulletSpeed = 500f;

    bool facingRight = true;
    Vector3 localScale;

    public Transform barrel;
    public Rigidbody2D bullet;

    // Use this for initialization
    void Start()
    {
        localScale = transform.localScale;
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        dirX = CrossPlatformInputManager.GetAxis("Horizontal");

        if (CrossPlatformInputManager.GetButtonDown("Jump"))
            Jump();

        if (CrossPlatformInputManager.GetButtonDown("Fire1"))
            Fire();
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
    }

   

    void Jump()
    {
        if (rb.velocity.y == 0)
            rb.AddForce(Vector2.up * jumpForce);
    }

    void Fire()
    {
        var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
        firedBullet.AddForce(barrel.up * bulletSpeed);
    }
}
1

1 Answers

0
votes

Hit Detection

For detecting if you hit an enemy with the bullet, add a trigger collider and a script to your bullet prefab with this code inside: This example will destroy the enemy gameObject if you hit it with a bullet.

private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "enemy")
        {
            // Do your code


            // For example
            Destroy(collision.gameObject);
        }
    }

Bullet Rotation

About you other question, you instantiate the bullet with barrel.position and barrel.rotation. Do you change the rotation of barrel when you change direction?